library (basic java beginer)
public class Book { String bookName,author; int bookId,noOfCopies; public String getBookName() { return bookName; } public void setBookName(String bookName) { this.bookName = bookName; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public int getBookId() { return bookId; } public void setBookId(int bookId) { this.bookId = bookId; } public int getNoOfCopies() { return noOfCopies; } public void setNoOfCopies(int noOfCopies) { this.noOfCopies = noOfCopies; } } import java.util.Scanner; public class Library { public static void main(String args[]) { LibraryImpl l1= new LibraryImpl(); int ch=0; do { System.out.println("Menu"); System.out.println("1.Add Books"); System.out.println("2.Add Student"); System.out.println("3.issue books"); System.out.println("4.return books"); System.out.println("5.search book"); System.out.println("Enter ur choice"); Scanner s=new Scanner(System.in); ch=s.nextInt(); switch(ch) { case 1: l1.addbooks(); break; case 2: l1.addstudent(); break; case 3: l1.issuebooks(); break; case 4: l1.returnbooks(); break; case 5: l1.searchbooks(); break; default: System.out.println("wrong choice"); } }while((ch>0) && (ch<6)); } } import java.util.ArrayList; import java.util.Scanner; public class LibraryImpl { ArrayList<Book> bookList=new ArrayList<Book>(); ArrayList<Student> stuList=new ArrayList<Student>(); int[] arr=new int[5]; public void addbooks() { Book b1=new Book(); System.out.println("Enter the name of the book"); Scanner s1=new Scanner(System.in); String name=s1.nextLine(); b1.setBookName(name); System.out.println("Enter book id"); int id=s1.nextInt(); b1.setBookId(id); System.out.println("enter author"); String author=s1.next(); b1.setAuthor(author); System.out.println("enter no of copies"); int copies=s1.nextInt(); b1.setNoOfCopies(copies); bookList.add(b1); } public void addstudent() { Student s1=new Student(); System.out.println("Enter the name "); Scanner sc1=new Scanner(System.in); String name=sc1.nextLine(); s1.setSname(name); System.out.println("Enter student id"); int id=sc1.nextInt(); s1.setSid(id); System.out.println("enter no of copies"); int copies=sc1.nextInt(); s1.setNoc(copies); stuList.add(s1); } public void issuebooks() { System.out.println("Enter book id"); Scanner sc=new Scanner(System.in); int id=sc.nextInt(); for(Book b:bookList) { if(b.getBookId()==id) { if(b.getNoOfCopies()== 0) System.out.println("Book not available"); else checkStud(b); } } } public void checkStud(Book obj) { System.out.println("Enter student id"); Scanner sc=new Scanner(System.in); int sid=sc.nextInt(); for(Student stud:stuList) { if(stud.getSid()==sid) { if(stud.getNoc()<5) { System.out.println("Book Issued"); stud.setNoc(stud.getNoc()+1); obj.setNoOfCopies(obj.getNoOfCopies()-1); } else System.out.println("Only 5 books can be issued"); } } } public void returnbooks() { System.out.println("Enter book id"); Scanner sc=new Scanner(System.in); int id=sc.nextInt(); for(Book b:bookList) { if(b.getBookId()==id) { b.setNoOfCopies(b.getNoOfCopies()+1); callStud(); } } } public void callStud() { System.out.println("Enter student id"); Scanner sc=new Scanner(System.in); int sid=sc.nextInt(); for(Student stud:stuList) { if(stud.getSid()==sid) { System.out.println("Book Returned"); stud.setNoc(stud.getNoc()-1); } else System.out.println("Invalid user"); } } public void searchbooks() { System.out.println("Enter the name of the book"); Scanner sc=new Scanner(System.in); String name=sc.next(); for(Book b:bookList) { if(b.getBookName().equalsIgnoreCase(name)) { System.out.println("The details are:"+b.getBookName()+" "+b.getAuthor()+" "+b.getNoOfCopies()); } } } } public class Student { String sname; int sid,noc; public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } public int getSid() { return sid; } public void setSid(int sid) { this.sid = sid; } public int getNoc() { return noc; } public void setNoc(int noc) { this.noc = noc; } }
Object Basics and Simple Data Objects
Arrays
An array is the collection of similar type of elements. In
java when the array variable is created its length i.e. the number of elements
in the array is fixed. As an example the portion args[] in main method you use
is an array, but here it is not of fixed length since it is an argument (more
on this later). However, if you want to have the record say name of the
students of your class, then you could declare like this:
String students = new String[30]; here we are defining the
array named students of length 30 i.e. we can store up to 30 students name. To
access an element in array we use the index (subscript) value of the particular
array and remember in Java the index starts with 0. So In the above example if
you want to access the name of 1st and 7th students, the
array uses the indices as students[0],
and students[6] respectively.
Example Piece of Code:
String myArray[] = {hello, iello, jello,
kello};
for(int i=0; i<4;i++)
System.out.println(myArray[i]);
The above code prints all the names in the new lines. Other
details are discussed later.
Variable
Declaration for Arrays
We declare variable by providing its type and its name. as
type[] varname; or type varname []; See the example below:
int intArray []; //this is the declaration of array of
integer no size is given.
Alternatively we can declare the above array as
int [] intArray; //this form is encouraged.
We can declare any type of array i.e. it may be the array of
objects like
String [] srtingArray;
Or it may be array of primitive type as previously shown.
You must always specify the number of elements in an array
for this purpose either we can create the array just by declaration or
initialize it as discussed in next section.
Initializing
Arrays and Accessing Arrays
To create an array we do the following:
double [] arrayDouble =
new double[10] // array of
double with 10 elements.
Or,
double [] arrayDouble;
arrayDouble = new double[10];
when an array is created we can initialize it after the
creation or within the declaration itself we can initialize it as shown below:
int [] myArray = {1, 2,
3, 4, 5};
This is initialization at the declaration time and at this
situation the size of the array is 5. Remember all the elements are enclosed
within the braces.
We could have done like this:
int [] myArray = new
int[5];
myArray[0] = 1;
myArray[1] = 2;
myArray[2] = 3;
myArray[3] = 4;
myArray[4] = 5;
Note: the index of
the element in array enclosed within brackets starts from 0.
Example Piece of Code
(Initializing and Accessing Arrays):
char [] charArray =
{‘a’, ’e’, ’i’, ‘o’ ‘u’};
for(int i = 0; i <
charArray.length; i++)
System.out.println(charArray[i]);
The above code prints all the vowels in lower case line by
line.
Copying
Arrays
To copy the array we can take advantage of the method defined
in the System class called arraycopy with the signature:
public static void
arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
Here src is source array, srcPos is position from where we
are copying, dest is destination array, destPos is position at the destination
array to start copying and length is the number of element to be copied.
Example Piece of Code:
int [] sourceArray = {1, 2, 3, 4, 5, 6,
7, 8, 9, 0 };
int [] destArray = new int[5];
System.arraycopy(sourceArray, 3,
destArray, 0, 5);
for(int i = 0; i < destArray.length; i++)
System.out.print(destArray[i]);
See the output it will be 45678
One-Dimensional
Arrays
All the discussions on an array above were described using
single dimensional array i.e. the elements are serially accessed and there is
only one row. However, we can create and use array with more than one
dimension. This aspect is discussed in next section.
Multi-Dimensional
Arrays
Multidimensional arrays are arrays of arrays. The
declaration, creation and initialization schemes are similar to the one
dimensional arrays but with subtle differences that can be easily seen from
below explanations. You can extend all the details as of above ones.
int array2D [][] = new int [6][7] //creation of array of dimension 6 by 7.
char charArray2D[2][3] = {‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’};
Or equivalently,
char charArray2D[][] = {{‘a’, ‘b’, ‘c’}, {‘d’, ‘e’, ‘f’}};
to access the array we use the same subscript form but there
is slight difference in that the two dimensional array starts from inner
subscripts to outer one.
Example Piece of Code:
char charArray2D[][] =
{{‘a’, ‘b’, ‘c’}, {‘d’, ‘e’, ‘f’}};
for(int i = 0; i < 2; i++) //for inner subscripts
{
for(j = 0; j < 3; j++) //for outer subscripts
System.out.print(charArray[i][j]);
System.out.println();
}
The output will be like
abc
def
When multidimensional array is created it is not necessary to
define memory for all dimensions. The definition for the first (leftmost)
dimension is sufficient. See below:
String str2D [][] = new String[3][];
str2D[0] = new String[2];
//the memory for the remaining dimension may differ. But str2D[1] = new
String[4]; // in normal
practice it is generally same
str2D[2] = new String[4];
Objects
If we just sit around the corner and think about the entities
in the real world we notice that every entity (whether we can identify it or
not vary) has its state and behavior. For e.g. let’s think about and object,
say student. If we consider some of the states of the student, then they many
be name, address, grade, sex, etc. And we can think of the behaviors can be
represented to answer what is the sex?, what is name and address? , etc. The
same concept of the real world can be applied in programming too so that we can
take advantage of natural interaction and representation of objects in the
software environment. So basic concept of object in programming is to
manipulate the states of the object using methods (what we call behavior in
general term) so that we can combine both fields and attributes in a pack and
let other possible user (object) use the object without knowing the internal
detail of an object through its behaviors. For e.g. we are objects and so are
other entities we use and if we use an object say bike, then we don’t care what
it consists of and how its constituents are assembled so that we can ride it.
The only thing we care for is what can be done to ride it. Here are some noted
advantages of using object oriented approach in programming (notice that these
points are already discussed in chapter 2):
Modularity:
Independent block of code can be written to represent an object. The
independent modules can be later combined to perform larger tasks thus
simplifying the programming task.
Information Hiding:
The objects are used only using its methods without revealing internal details.
Reuse: Once the
object is formalized in code we can reuse the same code if it is needed later
in our program. This reduces development time due to many factors like no
debugging required for reusable code, less coding required, etc.
Pluggability and
Debugging Ease: Since objects are implemented independently they can be
easily removed and placed in a program so that it will be easier for the
programmer to debug the program for possible portion of errors.
Classes
As we have discussed in chapter 2, a class is the framework
that defines the object. In Java objects are implemented as a class. We are not
going to define it more here. However, remember, since we can use different
objects for interaction we say a class as user defined data type or programmers
defined data type. Since we are going to implement objects using the class we
can understand that in the class we define state (now onwards fields or
variables) and behaviors (now onwards methods). Here is the simple skeleton of
a class definition (this is not the complete syntax for class declaration).
class className {
data-type variable1;
data-type variable2;
…
… //className , variable
names and method names are any valid identifirs.
data-type variablen;
data-type method1(zero
or more arguments) { … method definition…}
data-type method2(zero
or more arguments) { … method definition…}
…
data-type methodn(zero
or more arguments) { … method definition…}
}
In the above skeleton of class, data-type refers to any type
of data like primitives, user defined. In the place of data-type in methods a
special word called void can be
given to state that the method does not return a value, where as if usual data
type (like in variables) is used then the return type of the method is the
given type.
Example
class Rectangle {
int
length; //rectangle has two units
called length and breadth.
int
breadth;
int
getLength() { return length;}
int
getBreadth() {return breadth;}
int
findArea() {return length*breadth;}
int
findPerimeter() {return 2*(length+breadth);}
void
print(int x){System.out.println(x);}
}
Above we defined a class called Rectangle (convention: start with capital letter).
We can think that the object rectangle has two properties length and breadth
(declared as integer type). Now, the behaviors that are shown by the rectangles
are obtaining length, breadth, area and perimeter. These are implemented using
methods (convention: start with
verb, the following words start with capital letter). The class declaration
takes other keywords like public, private, final, abstract, etc and these terms
will be defined later.
Creating
Objects
The object of the class is created by using the new keyword. To get a usable object we
must finish two steps: declaring the object of its type and instantiating the
object. The following example shows the creation of an object of type
Rectangle.
Rectangle myRectangle; //declaring the variable of type Rectangle
The consequence of the above step creates the variable that
holds reference of the class Rectangle using the name myRectangle. It points
nowhere (i.e. null) as shown below:
When we perform the next step then the actual assignment of
object reference to the variable is done
as shown in above figure (right). We instantiate the object like:
myRectangle = new
Rectangle(); //Instantiating an
object
The above two steps are equivalently written as
Rectangle myRectangle =
new Rectangle();
Note: Each object
of the class has its own copy of the instance variables so changing variable
through one object does not affect the variables for the others.
We can create more than one reference for same object such
using different name we can manipulate same object. Here is how to do it.
Rectangle myRectangle =
new Rectangle();
Rectangle myRectangle1
= new Rectangle();
myRectangle =
myRectangle1;
The pictorial representation of above code segment is as
below:
Though myRectangle and myRectangle1 reference same object
they are not linked to each other so if we assign some other object to one of
the name later then it removes the previous link. For e.g. after some lines of
code from above if we write
myRectangle = null;
The name myRectangle now does not point to rectangle object.
new: As said
earlier new is used for creating an object. The main idea of using main is to
create the memory that is required to hold an object of the particular type in
run time i.e. to dynamically allocate the memory at the run time.
Using Class
Members
When an object of the class is created then the members are
accessed using the ‘.’ dot operator as shown below:
myRectangle.length =
5; //assigning 5 to length of an object
referenced by myRectangle.
int l =
myRectangle.getLength(); //calling
method to get length of an object referenced.
Program 4.1
class Rectangle {
int len;
int bre;
}
public class
MainRectClass4_1{
public static void main(String [] args) {
Rectangle rect1 = new Rectangle(); //constructor
Rectangle rect2 = new Rectangle();
rect1.len = 5;
rect1.bre = 10;
System.out.println("Areas\nFirst
rectangle: "+ rect1.len*rect1.bre);
rect2.len = 4;
rect2.bre = 15;
System.out.println("Second
rectangle: " + rect2.len*rect2.bre);
rect1 = rect2;
System.out.println("Now
first rectangle: “+ rect1.len*rect1.bre);
} }
Output
Areas
First rectangle: 50
Second rectangle: 60
Now first rectangle: 60
Methods
We use method in the class to perform some action. Every
method definition must have its return type, name and opening and closing
parenthesis. See above class Rectangle for method definition. The skeleton for
method definition is as given below:
data-type methodName
(parameter list) {
statements for method
definition;
}
data-type is return type, parameter list consists of list of
variables declared using data type used for passing to the methods definition
statements for manipulation. For example if we want user to enter two values
stored in x and y variables, and the method that returns their sum, then this
method can be written as:
int sum(int x, int y) { return x+y;}
Here our method takes two parameters (arguments) to carry out
the operations. The method name along with its parameter list is called the
signature of the method.
Getters and
Setters
To provide the interface for the user to modify and use the
fields (private) within the class we provide methods to get and set the values of
attributes rather than allow them to be modified directly. It has got different
reasons like validating the data, hiding the read only data, etc. The program
below gives an example with get and set methods.
Program 4.2
class Rectangle1 {
private
int length; //rectangle has two units
called length and breadth.
private
int breadth;
int
getLength() { return length;}
int
getBreadth() {return breadth;}
void
setBreadth(int b){breadth = b;}
void
setLength(int l){length = l;}
int
findArea() {return length*breadth;}
int
findPerimeter() {return 2*(length+breadth);}
void
print(){System.out.println(“Area = “+findArea());}
}
public class MainRectClass4_2{
public static void main(String [] args) {
int len, bre;
Rectangle rect1 = new Rectangle(); //constructor
Rectangle
rect2 = new Rectangle();
rect1.setLength ( 5);
rect1.setBreadth( 10);
System.out.println("
Area of first rectangle is " + rect1.findArea());
System.out.println("Perimeter
of first rectangle is " + rect1.findPerimeter());
rect2.setLength ( 4);
rect2.setBreadth( 15);
System.out.println("
Area of second rectangle is " + rect2.findArea());
System.out.println("Perimeter
of second rectangle is " + rect2.findPerimeter());
len = rect1.getLength();
bre = rect2.getBreadth();
System.out.println("Now
Area is: "+ len*bre);
rect1 = rect2;
System.out.print("Now
first rectangle's ");
rect1.print();
}
}
Output
Area of first rectangle
is 50
Perimeter of first
rectangle is 30
Area of second rectangle is 60
Perimeter of second
rectangle is 38
Now Area is: 75
Now first rectangle's
Area = 60
Note: you can have
only one public class within a file. If you put more than one public class it
is a compiler error.
Constructors
Initializing the values of the variables of the class is very
time consuming process. Though we have set methods that can be used to assign
values to the variables it is tedious too. So to remedy this complexity we can
take advantage of constructor for providing values to the instance variables in
the class. The constructor initializes the object immediately after its
creation and it will be simpler for us if we initialize variables while creating
the object. Constructor has same name as of class and looks like a method
except that it has no return type. We have already seen the use of the
constructor in above programs as Rectangle() [default constructor]. Though we
have used the constructor we have not defined it and if we do not define the
constructor the default constructor is called automatically. And if we define
constructor ourselves then there will be no default constructor so in case of
your need of default constructor you have to create by yourselves. Since
constructor looks like method we can provide arguments (parameters) to the
constructor and mainly parameters are used for providing the values to the
variables. The below program is modification of program 4.2 using our
constructor.
Program 4.3
class Rectangle2 {
private int length;
private int breadth;
void setBreadth(int b){breadth = b;}
void setLength(int l){length = l;}
Rectangle2(){/*default constructor does noting*/}
Rectangle2(int length, int breadth){this.length = length; this.breadth
= breadth;}
int findArea() {return length*breadth;}
}
public class MainRectClass4_3{
public
static void main(String [] args) {
Rectangle2
rect1 = new Rectangle2(); //default
constructor called
Rectangle2
rect2 = new Rectangle2(4,15);
rect1.setLength (5);
rect1.setBreadth(10);
System.out.println("
Area of first rectangle is " + rect1.findArea());
System.out.println("
Area of second rectangle is " + rect2.findArea());
} }
Output
Area of first rectangle
is 50
Area of second
rectangle is 60
this
Keyword
You must have notices that in our constructor definition
above there is a special symbol called this.
The keyword this can be used within
any method to represent the current object i.e. this is the reference to the object on which method is getting
invoked. For example see this code segment
void setLength(int
l){this.length = l;}
this definition is equivalent to the definition of setLength
method above. It tells us that the variable length is of the object calling the
method setLength.
Again if you look at the constructor definition above you see
the name length as both parameter
and instance variable. Though normally in java declaring two variables within
the same scope is illegal it is permissible to have same name as parameter of a
method and instance variables. This will hide the instance variables so to
identify the instance variable we use this
keyword as above.
Garbage
Collection
We use new keyword
to dynamically allocate the memory. Since the memory is created it must be
destroyed to free the space if the object is not referencing any memory
location. To do this task java takes a smarter approach (letting use relax)
that destroys the memory space used by the object whenever object is no longer
in use. The process of freeing up memory used by objects that are not used is
called garbage collection and this process is automatically done by java. It is
not true that whenever the object is not used java runs the garbage collector
but the garbage collector is run occasionally. Normally, we do not have to take
care about this thing in our programming. If you want to call the garbage
collector by youself then you can use the static method gc of the System class
as:
System.gc();
Remember, the above request the run of garbage collector. It
is not true that it forces the JVM to perform garbage collection.
Finalizer
When we need to perform some actions at the time of object
destruction then we can use the special method called finalize to do those actions. For e.g. if you are using some non
java resources like file handle in object’s constructor and we want to free the
handle before object destruction then we can use this concept. The finalize method is called just before
the garbage collection, has no parameter and has return type void. The main issue with finalize is that the garbage collector is not guaranteed
to execute at a specified time or it may never execute before a program
terminates. So the call of finalize is also not guaranteed. For this reason, it
is advisable to avoid finalize method.
The below code segments tells us the definition of finalizer.
protected void finalize() { System.out.printf( "object destroyed”); }
The access of the finalize method
is protected so that code outside the class cannot call this method. (more on
access specifiers later) .
Object’s
Life Cycle
We have learnt every basics of object and combining all the
details we can summarize the following as the life cycle of an object.
·
Object memory allocation
·
Initialization of variables
·
Call of constructor (appropriate one)
·
Use of object in program
·
Disassociation of reference to the memory by an
object
·
Garbage collection run
·
Calling the object's finalize (if any) method (by garbage
collector).
·
Memory freeing by garbage collector.
Using
Classes
Characters
and Strings
Character is the building block of the java programming. We
generally deal with the sequence of characters that when combined gives the
meaningful interpretation. String is a sequence of character that is treated as
a single unit. Some of the classes that are used to manipulate characters and
strings are discussed below. For more details refer to the Java Documentation.
The
Character Class
Character class is
the wrapper class that wraps the char
data type. The object of this class holds a single character value.
Constructor
Character(char value) :
This constructor constructs a newly allocated Character object that represents
the specified char value. E.g. Character
ch = new Character(‘x’);.
Some Useful
Methods
char charValue()
: Returns the primitive char value of
this Character object.
int compareTo(Character
anotherCharacter) : Compares two Character objects. The return value is 0
if two objects are numerically same, less than 0 if this object
is numerically less than anotherCharacter, greater than 0 if numerically
greater.
boolean equals(Object
obj) : Compares this object against
the specified object. The return value is true if the object is same as
Character object, false otherwise.
static boolean isDigit(char ch) : Determines if the
specified character is a digit.
static boolean isJavaIdentifierPart(char ch) :Determines
if the specified character may be part of a Java identifier.
static boolean isJavaIdentifierStart(char ch) :
Determines if the specified character can be the first character in a Java
identifier.
static boolean isLetter(char ch) : Determines if the
specified character is a letter.
static boolean isLetterOrDigit(char ch) : Finds if the given character is a letter or
digit.
static boolean isLowerCase(char ch) : Determines if the
specified character is a lowercase character.
static boolean isSpaceChar(char ch) : Determines if the
specified character is a Unicode space character.
static boolean isUpperCase(char ch) : Determines if the
specified character is an uppercase character.
static boolean isWhitespace(char ch) : Determines if the
specified character is white space according to Java.
static char
toLowerCase(char ch) : Converts the character argument to lowercase using
case mapping information from the UnicodeData file.
String toString() : Returns a String object (length 1)
representing this Character's value.
static char toUpperCase(char ch) :Converts the character
argument to uppercase using case mapping information from the UnicodeData file.
static Character
valueOf(char c) : Returns a Character instance representing the specified
char value. Similar to using the constructor.
Program 4.4
public class Character4_4 {
public static void
main(String [] args) {
Character
ch1 = new Character('x');
Character
ch2 = new Character('y');
Character
ch3 = new Character('z');
Character
ch4 = new Character(' ');
Character
ch5 = new Character('\t');
Character
ch6 = new Character('B');
Character
ch7 = Character.valueOf('1');
Character
ch8 = Character.valueOf('x');
int
difference = ch1.compareTo(ch2);
//comparing
two characters
if(difference
== 0)
System.out.println(ch1
+ " and "+ch2+" are same");
else
if(difference<0)
System.out.println(ch1
+ " is less than "+ch2);
else
System.out.println(ch1
+ " is greater than "+ch2);
// checking
the equality of two objects
System.out.println(ch1
+ " and "+ch8+" are same: "+ch1.equals(ch8));
//Other
methods check
System.out.println(ch1
+ " is digit? "+ Character.isDigit(ch1.charValue()));
System.out.println(ch3
+ " is letter ? "+ Character.isLetter(ch3.charValue()));
System.out.println(ch6 +
" is upper case? "+ Character.isUpperCase(ch6.charValue()));
System.out.println(ch3
+ " is lower case? " + Character.isLowerCase(ch3.charValue()));
System.out.println(ch4
+ " is whitespace? "+
Character.isWhitespace(ch4.charValue()));
System.out.println(ch5
+ " is space character? "+ Character.isSpaceChar(ch5.charValue()));
System.out.println(ch7
+ " is letter or digit? "+ Character.isLetterOrDigit(ch7.charValue()));
} }
Output
x is less than y
x and x are same: true
x is digit? false
z is letter ? true
B is upper case? true
z is lower case? true
is whitespace? true
is space
character? false
1 is letter or digit?
true
The String
Class
String class is
used to manipulate strings whose value will not change. They are represented by
sequence of characters within double quotes.
Some
Constructors
String() :
Initializes a newly created String object so that it represents an empty character
sequence.
String(byte[] bytes) :Constructs
a new String by decoding the specified array of bytes using the platform's
default charset.
String(byte[] bytes,
int offset, int length) : Constructs a new String by decoding the specified
subarray of bytes using the platform's default charset.
String(char[] value) :
Allocates a new String so that it represents the sequence of characters
currently contained in the character array argument.
String(char[] value,
int offset, int count) : Allocates a new String that contains characters
from a subarray of the character array argument.
String(String original)
: Initializes a newly created String object as a copy of the argument
string.
Some Useful
Methods
char charAt(int index) : Returns the char value at the specified index
. The index value starts from 0 to length()-1.
int compareTo(String
anotherString) : Compares two strings lexicographically. The return value
is 0 if the argument string is equal to this string, a value is less than 0 if
this string is lexicographically less than the string argument; and a value
greater than 0 if this string is lexicographically greater than the string
argument.
int compareToIgnoreCase(String str) : Compares two strings
lexicographically, ignoring case differences.
String concat(String str) : Concatenates the
specified string to the end of this string.
boolean
contentEquals(StringBuffer sb) : Returns true if and only if this String
represents the same sequence of characters as the specified StringBuffer.
static String
copyValueOf(char[] data) : Returns a String that represents the character
sequence in the array specified.
static String
copyValueOf(char[] data, int offset, int count) : Returns a String that
represents the character sequence in the array specified.
boolean endsWith(String
suffix) : Tests if this string ends with the specified suffix. boolean
equals(Object anObject) : Compares this string to the specified object.
boolean
equalsIgnoreCase(String anotherString) : Compares this String to another
String, ignoring case considerations.
byte[] getBytes() : Encodes this String into a
sequence of bytes using the platform's default charset, storing the result into
a new byte array.
int indexOf(int ch)
: Returns the index within this string of the first occurrence of the specified
character. -1 is returned if no character is found.
int indexOf(int ch, int
fromIndex) : Returns the index within this string of the first occurrence
of the specified character, starting the search at the specified index.
int indexOf(String str)
: Returns the index within this string of the first occurrence of the specified
substring.
int indexOf(String str,
int fromIndex) : Returns the index within this string of the first
occurrence of the specified substring, starting at the specified index.
int lastIndexOf(int ch)
: Returns the index within this string of the last occurrence of the specified
character.
int lastIndexOf(int ch,
int fromIndex) : Returns the index within this string of the last
occurrence of the specified character, searching backward starting at the
specified index.
int lastIndexOf(String
str) : Returns the index within this string of the rightmost occurrence of
the specified substring.
int lastIndexOf(String
str, int fromIndex) : Returns the index within this string of the last
occurrence of the specified substring, searching backward starting at the
specified index.
int length() :
Returns the length of this string.
String replace(char oldChar, char newChar) :
Returns a new string resulting from replacing all occurrences of oldChar in
this string with newChar.
String replaceFirst(String regex, String
replacement) : Replaces the first substring of this string that matches the
given regular expression with the given replacement.
boolean
startsWith(String prefix) : Tests if
this string starts with the specified prefix.
boolean
startsWith(String prefix, int toffset) : Tests if this string starts with
the specified prefix beginning a specified index.
String substring(int beginIndex) : Returns a new string that is a substring of
this string.
String substring(int beginIndex, int endIndex) :
Returns a new string that is a substring of this string.
char[] toCharArray() : Converts this string to a new character
array.
String toLowerCase() : Converts all of the characters
in this String to lower case using the rules of the default locale.
String toUpperCase() : Converts all of the
characters in this String to upper case using the rules of the default locale.
String trim() : Returns a copy of the string,
with leading and trailing whitespace omitted.
static String
valueOf(boolean b) : Returns the string representation of the boolean
argument. There are other methods with same name for other primitive types and
Object types.
static String
valueOf(char[] data) : Returns the string representation of the char array
argument.
static String
valueOf(char[] data, int offset, int count) : Returns the string
representation of a specific subarray of the char array argument.
static String
valueOf(Object obj) : Returns the string representation of the Object
argument.
Program 4.5
public class String4_5 {
public static void
main(String [] args) {
String str1
= "Welcome";
char
chArray[] = {'H','o','m','e'};
String str2
= new String(chArray);
String str3
= new String("Sanitarium");
String str4
= new String("welcome");
int
difference = str1.compareTo(str2);
if(difference
== 0)
System.out.println(str1
+ " and "+str2+" are same");
else
if(difference<0)
System.out.println(str1
+ " comes before "+str2);
else
System.out.println(str1
+ " comes after "+str2);
if(str1.compareToIgnoreCase(str4)
== 0)
System.out.println(str1
+ " and "+str4+" are same ignoring the case");
if(str1.compareTo(str4)
== 0)
System.out.println(str1
+ " and "+str4+" are same ");
else
System.out.println(str1
+ " and "+str4+" are not same ");
System.out.println(str1
+ ": character at 2 is "+ str1.charAt(2));
System.out.println(str3
+ " ends with ium? "+ str3.endsWith("ium"));
System.out.println("Index
of o at "+ str4 + " is "+ str4.indexOf('o'));
System.out.println("Substring
of "+ str3 + " begining at index 2 and ending at 7 is
" + str3.substring(2, 7));
System.out.println(str4
+ " with all uppercase is "+str4.toUpperCase());
System.out.println(str1
+ " and "+ str3+ " are equal? "+str1.equals(str3));
System.out.println(str1.concat("
".concat(str2.concat(" (".concat (str3.concat(")") )))));
} }
Output
Welcome comes after
Home
Welcome and welcome are
same ignoring the case
Welcome and welcome are
not same
Welcome: character at 2
is l
Sanitarium ends with
ium? true
Index of o at welcome
is 4
Substring of Sanitarium
begining at index 2 and ending at 7 is nitar
welcome with all
uppercase is WELCOME
Welcome and Sanitarium
are equal? false
Welcome Home
(Sanitarium)
The
StringBuffer Class
StringBuffer class
is similar to the String class but
we can modify the string using this class. This class is safe for using in
multithreaded environment.
Some
Constructors
StringBuffer() : Constructs a string buffer with no characters
in it and an initial capacity of 16 characters.
StringBuffer(int
capacity) : Constructs a string buffer with no characters in it and the
specified initial capacity.
StringBuffer(String
str) : Constructs a string buffer initialized to the contents of the
specified string.
Some Useful
Methods
StringBuffer
append(char c) : Appends the string
representation of the char argument to this sequence. There are methods with
same name for other primitive types, Object class type, String type and
StringBuffer type.
StringBuffer
append(char[] str) : Appends the string representation of the char array
argument to this sequence.
StringBuffer
append(char[] str, int offset, int len) : Appends the string representation
of a subarray of the char array argument to this sequence.
int capacity() :
Returns the current capacity. The capacity is the amount of storage available
for newly inserted characters, beyond which an allocation will occur.
StringBuffer delete(int
start, int end) : Removes the characters in a substring of this sequence.
StringBuffer
deleteCharAt(int index) : Removes the char at the specified position in
this sequence.
StringBuffer insert(int offset, boolean b) : Inserts
the string representation of the boolean argument into this sequence at
indicated offset. There are methods with same name for other primitive types,
Object class type and String type.
StringBuffer insert(int offset, char[] str) :
Inserts the string representation of the char array argument into this
sequence.
StringBuffer insert(int index, char[] str, int offset,
int len) : Inserts the string representation of a subarray of the str array
argument into this sequence.
StringBuffer replace(int start, int end, String str)
: Replaces the characters in a substring of this sequence with characters in
the specified String.
void setCharAt(int index, char ch) : The
character at the specified index is set to ch.
void setLength(int newLength) : Sets the
length of the character sequence.
void trimToSize() : Attempts to reduce storage
used for the character sequence. This is effective is buffer capacity is higher
than length of the string.
char charAt(int index),
int indexOf(String str) , int indexOf(String str, int fromIndex) , int
lastIndexOf(String str) , int lastIndexOf(String str, int fromIndex) , int length() , String substring(int start),
String substring(int start, int end) : Similar as of String class
Program 4.6
public class StringBuffer4_6 {
public static void
main(String [] args) {
StringBuffer
str1 = new StringBuffer("Six fert ppp");
System.out.println(str1);
str1.delete(6,
str1.length());
System.out.println("Buffer
Capacity = "+ str1.capacity());
System.out.println(str1);
str1.append("Under");
System.out.println(str1);
str1.insert(6,"et ");
System.out.println(str1);
str1.setCharAt(4,'F');
System.out.println(str1);
Str1.trimToSize();
System.out.println("Trimmed
Buffer Capacity = "+ str1.capacity());
} }
Output
Six fert ppp
Buffer Capacity = 28
Six fe
Six feUnder
Six feet Under
Six Feet Under
Trimmed Buffer Capacity
= 14
The
StringTokenizer Class
StringTokenizer
class (from java.util package)
allows us to break a string into tokens. This class can be used, for example,
in the situation where we have our data separated by commas but we do not need
commas in our application.
Constructors
StringTokenizer(String
str) : Constructs a string tokenizer for the specified string. The tokenizer uses the default delimiter set,
the space character, the tab character, the newline character, the
carriage-return character, and the form-feed character. Delimiter characters
themselves will not be treated as tokens. Throws NullPointerException if the
String is null. Same for other constructors.
StringTokenizer(String
str, String delim) : Constructs a string tokenizer for the specified string
with the given delimeter set.
StringTokenizer(String
str, String delim, boolean returnDelims) : Constructs a string tokenizer
for the specified string. If the returnDelims is true delimiters are treated as
tokens and each delimiter is treated as string of length 1.
Methods
boolean
hasMoreElements() : Returns the same value as the hasMoreTokens method.
boolean hasMoreTokens()
: Tests for tokens availability from this tokenizer's string.
int countTokens() :
Calculates the number of times that this tokenizer's nextToken method can be
called before it generates an exception. Throws NoSuchElementException if there
are no more tokens in this tokenizer's string.
Object nextElement() : Returns the same value as
the nextToken method, except that its declared return value is Object rather
than String. Throws
NoSuchElementException if there
are no more tokens in this tokenizer's string.
String nextToken() : Returns the next token from
this string tokenizer. Throws NoSuchElementException if there are no more
tokens in this tokenizer's string.
String nextToken(String delim) : Returns the
next token in this string tokenizer's string. Throws NoSuchElementException if
there are no more tokens in this tokenizer's string.
Program 4.7
import java.util.*;
public class StringTokenizer4_7 {
public static void
main(String [] args) {
String source = "This,is
BBIS;II,year class";
StringTokenizer st = new
StringTokenizer( source, " ,;", false );
while( st.hasMoreTokens() ) {
String
value = st.nextToken();
System.out.print(
value + " ");
}
} }
Output
This is BBIS II year class
The
StringBuilder Class
StringBuilder
class is very similar to the StringBuffer
class with API compatible to StringBuffer
class. Use of this class is suggested in the single threaded application where StringBuffer has been used. We will not
discuss this class further in this class.
We
can use a number of classes in Java to work with numbers. The following figure
shows the classes that can be used to work on with numbers. At the top is the
abstract class Number.
We have already seen the wrapper class. Let’s briefly talk
about the uses of type wrapper classes. Whenever we need to have an object for
primitive type data we can use wrapper classes so that we can take advantage of
the capabilities that can be provided by classes like using different methods
for converting values to other types like primitive types, Strings, etc and
using defined variables like MIN_VALUE
and MAX_VALUE.
The two other classes in the figure BigInteger and BigDecimal
(in java.math package) classes
provides the capability of defining arbitrary precision numeric values.
Some Common
Methods
byte byteValue(),
double doubleValue(), float floatValue(), int intValue() , long longValue(),
short shortValue() : These methods
convert the values of this object to primitive data types as given by the name.
int compareTo(OBJ (same as of using object) val)
: Compares this object with the specified object val of the same type (OBJ is
not a keyword for clarification I have put it so as to represent object of the
same type).
boolean equals(Object x) : Compares this object
with the specified Object for equality.
All the wrapper classes have some common fields defined as
public static. Some of them are MIN_VALUE
and MAX_VALUE. Usage e.g. Integer.MAX_VALUE.
Conversion
of String to Numbers and Vice Versa
Converting string to numeric type is just the matter of using
a method of the wrapper classes of that type. For e.g. if we want to convert
string to integer then we can use valueOf(String s // argument may be primitive
type of the wrapper class being used) or parseInt(String s) methods as
int num =
Integer.valueOf(“14”); or int
num = Integer.parseInt(“14”);
You can extend this concept to any other wrapper classes
where in parse method the last words are name of the primitive types like
parseDouble, parseByte, etc.
If we want to convert any number to String just use toString
method of that class. E.g. Double.toString(“14.43”); /*argument is value of the same type in
primitive form i.e. signature for above method is static String toString(double d) in Double class*/
Program 4.8
public class Numbers4_8 {
public static void
main(String [] args) {
Double dob1
= new Double("43.656");
double x =
Double.valueOf(dob1);
double y =
Double.parseDouble("34.323");
System.out.print(
Double.toString(x+y));
} }
Output
77.979
Math Class
Before concluding the chapter let’s briefly see methods (
they are all static) provided by Math class
so that we can use them while working with numbers. This class contains methods
for performing basic numeric operations such as the elementary exponential,
logarithm, square root, and trigonometric functions.
Fields
static double E : The double value that is closer than
any other to e (2.718281828459045), the base of the natural logarithms.
static double PI : The double value that is closer
than any other to pi (3.141592653589793), the ratio of the circumference of a circle
to its diameter.
Some
Instance Methods (All Static Methods)
double abs(double a) ,
float abs(float a) , int abs(int a) , long abs(long a) : Each method
returns the absolute value of a given argument value.
double acos(double a) : For arc cosine of an
angle, in the range of 0.0 to pi.
double asin(double a) : For arc sine of an angle,
in the range of -pi/2 to pi/2.
double atan(double a) : For arc tangent of an
angle, in the range of -pi/2 to pi/2.
double atan2(double y, double x) : Converts
rectangular coordinates (x, y) to polar (r, q).
double cbrt(double a) : Returns the cube root of a
double value.
double ceil(double a) : Returns the smallest
(closest to negative infinity) double value that is greater than or equal to
the argument and is equal to a mathematical integer.
double cos(double a), double tan(double a) , double sin(double
a) : Returns trigonometric cosine, tangent and sine of the angle given
respectively.
double cosh(double x), double sinh(double x), double tanh(double x) : Returns the
hyperbolic cosine, sine and tangent of a double value respectively.
double exp(double a) : Returns Euler's number e
raised to the power of a double value.
double floor(double a) : Returns the largest
(closest to positive infinity) double value that is less than or equal to the
argument and is equal to a mathematical integer.
double log(double a) :
Returns the natural logarithm (base e) of a double value.
double log10(double a) :
Returns the base 10 logarithm of a double value.
double max(double a, double b), float max(float a, float b) , int max(int a,
int b), long max(long a, long b)
: Returns the greater of two
values.
double min(double a, double b), float min(float a, float b) , int min(int a,
int b), long min(long a, long b)
: Returns the smaller of two
values.
double pow(double a, double b) : Returns the value
of the first argument raised to the power of the second argument.
double random() : Returns a double value with a
positive sign, greater than or equal to 0.0 and less than 1.0.
double rint(double a) : Returns the double value
that is closest in value to the argument and is equal to a mathematical
integer.
long round(double a), int round(float a)
:Returns the closest long or closest int to the argument.
double sqrt(double a) : Returns correctly rounded
positive square root of a double value.
double toDegrees(double angrad) : Converts an
angle measured in radians to an approximately equivalent angle measured in
degrees.
double toRadians(double angdeg) : Converts an
angle measured in degrees to an approximately equivalent angle measured in
radians.
Exercises
1.
Do the exercises from the tutorial Classes and Objects
section and Number and String section.
2.
Write a program to find number of people, the number of
people with height greater than 150 cm and weight 50 kg and the number of
people with other height and weight combinations. Store height and weight of
some people say 20.
3.
Create a class called “Box” with fields width, height
and depth and methods to find volume and surface area. Use suitable
constructors. Implement the class to find volume and surface area of two boxes.
4.
Write a program to add two distances, where each
distance contains feet and inches as the fields. Also compare the distances.
(use class)
5.
Write a program that calculates percentage and GPA of
12 students. Each of the student has following attributes: name, class,
rollnum, marks obtained in 5 subjects.
6.
Create a class called “Time” with three attributes
hours, minutes, and seconds. Use appropriate constructor and display the time
in hh:mm:ss format. Modify the class to ass two time object that correctly
results in addition of time.
7.
Write a program to compare two number objects and print
the result based on their difference.
8.
Write a program to do the following:
a.
Find the sum and average of 10 numbers stored.
b.
Find the minimum and maximum among them.
c.
Sorts the elements in ascending and descending orders.
d.
Adds the two matrices.
e.
Calculate the percentage obtained by student.
Assumption can be 7 subjects with 100 full marks. Print the division obtained.
f.
Calculates the factorial of a number
g.
Search an element from an array using sequential and
binary search.
9.
Write a program that does the following:
a.
Converts a letter from a lowercase to uppercase.
b.
Converts the string of uppercase to string of lowercase
c.
Finds substring of “Reminder” from index 2 with length
5.
d.
Finds a character at position 5 in above string.
e.
Appends an integer at the end of the string.
10. Write
a program to identify the string as palindrome or not.
11.(Airline Reservations System) A small airline has just
purchased a computer for its new automated reservations system. You have been
asked to develop the new system. You are to write an application to assign
seats on each flight of the airline's only plane (capacity: 10 seats).Your
application should display the following alternatives: Please type 1 for First Class
and Please type 2 for
Economy. If the user types 1, your application should assign a seat in the
first-class section (seats 15). If the user types 2, your application should assign a seat
in the economy section (seats 610). Your application should then display a
boarding pass indicating the person's seat number and whether it is in the
first-class or economy section of the plane. Use a one-dimensional array of primitive
type boolean to
represent the seating chart of the plane. Initialize all the elements of the
array to false
to indicate that all the seats are empty. As each seat is assigned, set the
corresponding elements of the array to true to indicate that the seat is no longer
available. Your application should never assign a seat that has already been
assigned. When the economy section is full, your application should ask the
person if it is acceptable to be placed in the first-class section (and vice
versa). If yes, make the appropriate seat assignment. If no, display the
message "Next flight
leaves in 3 hours."
12. (Total Sales) Use a two-dimensional array to solve the
following problem: A company has four salespeople (1 to 4) who sell five
different products (1 to 5). Once a day, each salesperson passes in a slip for
each type of product sold. Each slip contains the following:
a.
The salesperson number
b.
The product number
c.
The total dollar value of that product sold that day
Thus,
each salesperson passes in between 0 and 5 sales slips per day. Assume that the
information from all the slips for last month is available. Write an
application that will read all this information for last month's sales and
summarize the total sales by salesperson and by product. All totals should be
stored in the two-dimensional array sales. After processing all the information for
last month, display the results in tabular format, with each column
representing a particular salesperson and each row representing a particular
product. Cross-total each row to get the total sales of each product for last
month. Cross-total each column to get the total sales by salesperson for last
month. Your tabular output should include these cross-totals to the right of
the totaled rows and to the bottom of the totaled columns.
13. What
is the purpose of keyword new? Explain what happens when this keyword is used
in an application.
14. What
is a default constructor? How are an object's instance variables initialized if
a class has only a default constructor?
15. Explain
the purpose of an instance variable.
16. Most
classes need to be imported before they can be used in an application. Why is
every application allowed to use classes System and String without first
importing them?
17. Explain
why a class might provide a set method and a get method for an instance
variable.
18. Create
a class called Invoice that a hardware store might use to represent an invoice
for an item sold at the store. An Invoice should include four pieces of
information as instance variables a part number (type String), a part
description (type String), a quantity of the item being purchased (type int)
and a price per item (double). Your class should have a constructor that
initializes the four instance variables. Provide a set and a get method for
each instance variable. In addition, provide a method named getInvoiceAmount
that calculates the invoice amount (i.e., multiplies the quantity by the price
per item), then returns the amount as a double value. If the quantity is not
positive, it should be set to 0. If the price per item is not positive, it
should be set to 0.0. Write a test application named InvoiceTest that
demonstrates class Invoice's capabilities.
19. Create
a class called Employee that includes three pieces of information as instance
variables a first name (type String), a last name (type String) and a monthly
salary (double). Your class should have a constructor that initializes the
three instance variables. Provide a set and a get method for each instance
variable. If the monthly salary is not positive, set it to 0.0. Write a test
application named EmployeeTest that demonstrates class Employee's capabilities.
Create two Employee objects and display each object's yearly salary. Then give
each Employee a 10% raise and display each Employee's yearly salary again.
20. Create
a class called Date that includes three pieces of information as instance
variables a month (type int), a day (type int) and a year (type int). Your
class should have a constructor that initializes the three instance variables
and assumes that the values provided are correct. Provide a set and a get
method for each instance variable. Provide a method displayDate that displays
the month, day and year separated by forward slashes (/). Write a test
application named DateTest that demonstrates class Date's capabilities.
Subscribe to:
Posts (Atom)
Search this blog
Real-Time statistics by EagleStats
Basic
Popular Posts
-
Here is the simple program in java and this can be written in any available text pads like notepad, wordpad, etc. 1. public class...
-
//import javautil public class Array{ public static void main(String args[]){ int myArray[]={1,2,3,4,5}; for (int i=0;i<5;i+...
-
Here are some terms that are used for java as its features: Simple Java syntax is similar to C and C++, however, most of the poorly ...
-
Arrays An array is the collection of similar type of elements. In java when the array variable is created its length i.e. the number of...
-
public class Book { String bookName , author ; int bookId , noOfCopies ; public String getBookName () { ret...
-
Java Language Basics Java program is a collection of different atomic elements namely, whitespace, identifiers, literals, comments, op...
-
This chapter briefly discusses different concepts that are pertaining to an object oriented programming. However, all the related deta...
-
Java Technology in Small and Mobile Devices The Micro Edition of the Java Platform meets the needs of developers creating applicatio...
-
Java Java is general purpose, object oriented, high-level programming language. It is used to develop different applications that run i...