Java
Java
Unit – 2 Department of IT
Prof. Tarannum
Bloch
Group oflike-typed variables
Arrays
Advantages ofArray
• Wecanstore multiple elements of the sametype under asingle
variable.
• Wecanimplement other data structures suchasStack,Queue,
Tree, etc. with the help of anarray.
• Wecanfetch data elements usingthe index at run time.
Arrays Example:
month_days = new int[12];
int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31,30, 31};
This is called compile-time initialization OR static
initialization of array.
1. int array1[]= {5,10,15,20,25};
a[0]=10;//initialization
a[1]=20;
Example a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
int twoD[][] = new int[4][5]
Multi-
dimensional
Arrays
Obtaining
length of2-D
Array
class MultidimensionalArray {
public static void main(String[] args) {
// create a 2d array
int[][] a = {
{1, 2, 3},
{4, 5, 6, 9},
{7},
};
OUTPUT
Length of row 1: 3
Length of row 2: 4
Length of row 3: 1
Processing 2-
D Arrays
Processing 2-
D Arrays
m[0].length meaning the number of columns in row 0
String is basically an object that represents sequence of char values. An array of
characters works same as Java string.
char[] ch={'j','a','v','a','p',‘r',‘o',‘g',‘r‘,’a’,’m’};
String s=new String(ch);
String is same as
String s="javaprogram";
Java String class provides a lot of methods to perform operations on strings such
as compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(),
substring() etc.
java.lang.Stringclassprovidesalot of methodsto work on a string.
String Class
The CharSequence interface is used to represent the sequence of
characters.
String s1="Welcome";
String s2="Welcome";//It doesn't create a new instance
Why Java uses the concept of String literal?
How to create
To make Java more memory efficient (because no new objects
a string are created if it exists already in the string constant pool).
object?
2. By new keyword
String Class
Constructors 2. Stringobject using anarrayofCharacters
• String(char charArray[ ])
• char Name[ ] ={‘J’, ‘A’, ‘V’, ‘A’, ‘P’, ‘R’, ‘O’, ‘G’};
• StringstrName =newString(Name);
3. StringObject Initialized by rangefrom char array
String(char charArray[ ],intstartindex, intno_of_char)
4. Stringobject usinganotherStringObject:
• String (StringstrObject);
• char Name[ ] ={‘J’, ‘A’, ‘V’, ‘A’, ‘P’, ‘R’, ‘O’, ‘G’};
• StringstrName =newString(Name);
StringstrName2 =newString(strName);
StringLiterals:
•char Name[ ] ={‘J’, ‘A’, ‘V’, ‘A’, ‘P’, ‘R’, ‘O’, ‘G’};
String Class • StringstrName =newString(Name);
OR
• String strName= “JAVAPROG”;
•Thelength()method returns the length of the string.
Ex:System.out.println(“Hello”.length());// prints 5
char ch;
ch=“abc”.charAt(1); // ch=“b”
getChars() -Copiescharacters from this string into the
destination characterarray.
Output
tarannum h
equals()-Comparesthe invoking string to the specified object.
The result is true if and only if the argument is not null and
is a String object that represents the same sequence of
charactersas the invokingobject.
“figure”.startsWith(“gure”,2);// true
compareTo() - Comparestwo strings lexicographically.
Theresult is anegative integer if this String object
lexicographically precedesthe argument string.
//passing substring
int index1=s1.indexOf("is");//returns the index of is substring
int index2=s1.indexOf("index");//returns the index of index substring
String System.out.println(index1+" "+index2);//
String
Eg:"unhappy".substring(2)
Operations returns "happy"
1 char charAt(int index) returns char value for the particular index
4 String substring(int beginIndex, int returns substring for given begin index and end index.
endIndex)
5 boolean contains(CharSequences) returns true or false after matching the sequence of char value.
Summary 7 boolean equals(Object another) checks the equality of string with the given object.
(0 <= Math.random()<1.0)
Math.random()
• Ex.(int)(Math.random() * 10)- - >Returnsarandom
integer between 0and9.
• a+Math.random() * b - - >Returnsarandom number
betweenaand a+b, excludinga+b.
• Ex.50+(int)(Math.random() * 100)- - >Returnsa
randominteger between 50and99.
• AStringBuffer is like aString, but can be modified.
• StringBuffer()
• StringBuffer(intsize)
• StringBuffer(Stringstr)
The principal operations on a StringBuffer are the append and insert
methods, which are overloadedsoasto accept data ofany type.
Index specifies at which point the string will be inserted into the
invokingStringBuffer object.
delete() - Removes the characters in a substring of this
StringBuffer. Thesubstring begins at the specified start and extends
to the character at index end - 1or to the end of the StringBuffer if
StringBuffer no such character exists. If start is equal to end, no changes are
made.
public StringBufferreverse()
StringBuffer
length()-Returnsthe length of this string buffer.
public intcapacity()
StringBuffer
charAt()-The specified character of the sequencecurrently
represented by the string buffer, as indicated by the index
argument, isreturned.
Summary
5 reverse() It can reverse the characters within a StringBuffer
object
6 delete(int startIndex, It can delete characters within a StringBuffer by using
int endIndex) the methods delete( )
7 replace() t can replace one set of characters with another set
8 indexOf(String str) This method returns the index within this string of the first
occurrence of the specified substring.
9 lastIndexOf(String str) This method returns the index within this string of the
last occurrence of the specified substring.
10 substring(int start) This method returns a new String that contains a
subsequence of characters
public class buffer {
public static void main(String[] args)
{
StringBuffer a = new StringBuffer(“stringbuffer”);
a.append(“in Java”);
System.out.println(a);
a.append(0);
System.out.println(a);
}
}
import java.io.*;
public class buffer {
public static void main(String[] args)
{
StringBuffer a = new StringBuffer(“stringbuffer”);
a.insert(5, “for”);
System.out.println(a);
a.insert(0, 5);
System.out.println(a);
a.insert(3, false);
System.out.println(a);
a.insert(5, 41.55d);
System.out.println(a);
a.insert(8, 41.55f);
System.out.println(a);
char arr[] = { ‘j’, ‘a’, ‘v’, ‘a’ };
a.insert(2, arr);
System.out.println(a);
}
}
import java.io.*;
public class buffer {
public static void main(String[] args)
{
StringBuffer a = new StringBuffer(“stringbuffer”);
a.replace(5, 8, “are”);
System.out.println(a);
}
}
output
strinareffer
String
Vs.
StringBuffer
• All Objects will be stores at HeapArea.
• String Constant Pool or String Literal Pool is an area in heap
memory where java stores String literal values.
== &equals •== operator always compare address or reference.
method • Equals method always compares Content.
difference
The wrapper class in Java provides the mechanism to convert
primitive into object and object into primitive.
Boolean, ByteClass:
Byte,Short static byte parseByte(String s,int radix)
static byte parseByte(String s)
Class
ShortClass:
shortValue()
isLowerCase() & isUpperCase()
static booleanisLowerCase(char ch)
staticboolean isUpperCase(char ch)
Ex.Characterc=newCharacter(‘g’);
boolean isLower= Character.isLowerCase(c);
Character isDigit( )
class static boolean isDigit(charch)
Ex. boolean isDigit= Character.isDigit(‘7’);
isSpace()
static boolean isSpace(charch)
Ex. boolean isSpace =Character.isSpace(‘\t’);
toLowerCase( ) & toUpperCase( )
static char toLowerCase(char ch)
static char toUpperCase(charch)
Ex. char c1 = Character.toUpperCase(‘g’);
char c2 =Character.toLowerCase(‘M’);
digit( )
Character static int digit(char ch, int radix)
class Ex. char c1 =‘4’;
char c2 =‘c’;
int four =Character.digit(c1,10);
int twelve =Character.digit(c2,16);
forDigit( )
static char forDigit(int digit, int radix)
int i=10;
char c =Character.forDigit(I,16);
Integer & Long Class
parseInt( )
static int parseInt(String s, int radix)
Integer static int parseInt(String s)
& Ex. Integer i = new Integer(17);
float f = i.floatValue();
LongClass
getInteger( )
static Integer getInteger(String name)
static Integer getInteger(String name, int val)
static Integer getInteger(String name, Integer val)
Float & Double Class:
isNaN( )
boolean isNaN( )
static boolean isNaN(floatv)
Ex. Double d1 = newDouble(23.70);
Float System.out.println(“is d1 is not a number?”
+d1.isNaN());
& isInfinite( )
DoubleClass boolean isInfinite( )
static boolean isInfinite(floatv)
VoidClass:
void class has no constructors or methods & only one
member constantTYPE.
• Theautomatic conversionof primitive datatype into its
correspondingwrapperclassisknownasautoboxing.
Forexample,byte to Byte,charto Character,int to Integer, longto Long,float
to Float,booleanto Boolean,doubleto Double,andshortto Short.
SinceJava5,wedonot needto usethe valueOf()methodof wrapperclassesto
converttheprimitive into objects.
Integerj=a;
//autoboxing, now compiler will write Integer.valueOf(a) internally
classGenerateRandom
{
public static void main(String args[] )
{
Randomrand =new Random(); //instanceof random class
The arguments passed from the console can be received in the java program
and it can be used as an input.
Command So, it provides a convenient way to check the behavior of the program for the
different values. You can pass N (1,2,3 and so on) numbers of arguments
Line from the command prompt.
Abstract List
class
methods
Declaration:
public abstract class AbstractList<E> extends AbstractCollection<E>
implements List<E>
Constructor:
protected AbstractList() – The default constructor, but being protected, it
doesn’t allow to create an AbstractList object.
Abstract List
class AbstractList<E> al = new ArrayList<E>();
Java ArrayList class uses a dynamic array for storing the elements. It is like
an array, but there is no size limit. We can add or remove elements
anytime. So, it is much more flexible than the traditional array. It is found in
Array List the java.util package. It is like the Vector in C++.
The ArrayList in Java can have the duplicate elements also. It implements the
List interface so we can use all the methods of the List interface here. The
ArrayList maintains the insertion order internally.
Array List
Array List
Methods
Array List
Methods
Array List
Methods
Java LinkedList class uses a doubly linked list
to store the elements. It provides a linked-list
data structure. It inherits the AbstractList
class and implements List and Deque
interfaces.
Constructors
Linked List
Methods
Linked List
Methods
Linked List
Methods
Linked List
Methods
1. Iterator
2. Enumeration
3. ListIterator
Enumeration Enumeration is It is an interface used to get elements of legacy
Iterative collections(Vector, Hashtable). Enumeration is the first iterator present
from JDK 1.0, rests are included in JDK 1.2 with more functionality.
Statements
Enumerations are also used to specify the input streams to a
SequenceInputStream. We can create an Enumeration object by calling
elements() method of vector class on any vector object .
Enumeration e = v.elements();
here are two methods in the Enumeration interface namely :
2. public Object nextElement(): This method returns the next element of this
enumeration. It throws NoSuchElementException if no more element is
Enumeration present.
Iterative
Methods
Vector is like the dynamic array which can grow or shrink its size. Unlike array,
we can store n-number of elements in it as there is no size limit. It is a part of
Java Collection framework since Java 1.2. It is found in the java.util package and
implements the List interface, so we can use all the methods of List interface
here.
• Vector is synchronized.
• Java Vector contains many legacy methods that are not the part of a
collections framework.