0% found this document useful (0 votes)
29 views18 pages

ENotes 1253 Content Document 20250117092736AM

This document covers Java programming concepts related to arrays, strings, wrapper classes, and utility classes. It explains the structure and initialization of one-dimensional and multidimensional arrays, string handling using String and StringBuffer classes, and the use of wrapper classes for converting between primitive types and objects. Additionally, it introduces the Java Collection framework and the Calendar class for date and time manipulation.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views18 pages

ENotes 1253 Content Document 20250117092736AM

This document covers Java programming concepts related to arrays, strings, wrapper classes, and utility classes. It explains the structure and initialization of one-dimensional and multidimensional arrays, string handling using String and StringBuffer classes, and the use of wrapper classes for converting between primitive types and objects. Additionally, it introduces the Java Collection framework and the Calendar class for date and time manipulation.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

BCA SEM 4 Prof.

Aayushi Shah
JAVA PROGRAMMING

CHAPTER 5

Arrays:
 An array is a group of same typed elements that are referred to by a common
name.
 It is used for grouping related information.
 A specific element in an array is accessed by its index.

One-Dimensional Arrays:
 A one-dimensional array is a list of same typed variables.
 Creating an array is a three steps process:
1. Array declaration.
 It can be done in two different ways:
type arrayname[]; example, int arr[];
or
type[] arrayname; example, int[] arr;
 No need to enter size at the time of declaration.
 Now, arr is an array with no values.
2. Creation of memory locations.
 This can be done using new operator.
arraname = new type[size];
example, arr = new int[10];
 Now, arr is linked with an actual, physical array of integers.
 This is done using keyword new.
3. Store values in array.
 This can be done by specifying index number of the element.
Example, arr[0] = 5;

 First, two steps can be combined into one.


int[] arr = new int[10];

 new is a special operator that allocates memory.


 Thus, in Java all arrays are dynamically allocated.
 The elements in the array allocated by new will automatically be initialized to
zero.
 Once an array ha s been allocated, it specific element in the array can be accessed
by its index.
 All array indexes start at zero.

-1-
BCA SEM 4 Prof. Aayushi Shah
JAVA PROGRAMMING

// Demonstrate a one-dimensional array.


class AutoArray
{
public static void main(String args[])
{
int numbers[] = new int[50];
for (int i = 0 ; i<50; i++)
{
if (i % 2 == 0)
numbers[i] = 1;
else
numbers[i] = 0;
}
for(int i = 0; i<50;i++)
System.out.print(numbers[i]+" ");
System.out.println( );
}
}
 Arrays can be initialized when they are declared.
 This can be done by specifying a list of comma-separated elements or expressions
surrounded by curly braces.
 The array will automatically be created large enough to hold the number of
elements specified in the curly braces. There is no need to use new.
class AutoArray
{
public static void main(String args[])
{
int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
System.out.println("April has " + month_days[3] + " days.");
}
}
 The Java run-time system will check to make sure that all array indexes are in the
correct range.
 Java does not allow to store or reference values outside of the range of the array.
 Accessing elements outside the range of the array (negative numbers or numbers
greater than the length of the array), will cause a run-time error.
.
Multidimensional Arrays:

 In Java, multidimensional arrays are arrays of arrays.


 Declaration of a multidimensional array,
double twoD[][] = new int[4][5];

-2-
BCA SEM 4 Prof. Aayushi Shah
JAVA PROGRAMMING

// Demonstrate a two-dimensional array.


class TwoDArray
{
public static void main(String args[])
{
int twoD[][]= new int[4][5];
int i, j, k = 0;
for(i=0; i<4; i++)
{
for(j=0; j<5; j++)
{
twoD[i][j] = k;
k++;
}
}
for(i=0; i<4; i++) {
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
This program generates the following output:
01234
56789
10 11 12 13 14

-3-
BCA SEM 4 Prof. Aayushi Shah
JAVA PROGRAMMING

15 16 17 18 19
 In case of memory allocation for a multidimensional array, you need only specify
the memory for the first (leftmost) dimension, remaining dimensions can be
specified separately.
 For example, this following code allocates memory for the first dimension of two
dimensional array, when it is declared. It allocates the second dimension
manually.
int arr[][] = new int[3][];
arr[0] = new int[4];
arr[1] = new int[4];
arr[2] = new int[3];
arr[3] = new int[2];
 Allocating dimensions manually, does not need to allocate the same number of
elements for each dimension.
 Following program creates a two dimensional array in which the sizes of the
second dimension are unequal.
class TwoDAgain
{
public static void main(String args[])
{
int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<i+1; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<i+1; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
This program generates the following output:
0
12
345
6789

 It is possible to initialize multidimensional arrays.


 In java arrays are implemented as objects.

-4-
BCA SEM 4 Prof. Aayushi Shah
JAVA PROGRAMMING

 Number of elements that an array can hold is stored in its length instance
variable. All arrays have this variable, and it will always hold the size of the array.
Example, int n = arr.length; will store size of arr array in variable n.

For each Loop


As of java 5 the enhanced for loop was introduced. This is mainly
used for Arrays.
• Syntax:
for(declaration : expression)
{
//Statements
}
• Declaration . The newly declared block variable, which is of a
type compatible with the elements of the array you are
accessing. The variable will be available within the for block and
its value would be the same as the current array element.
• Expression . This evaluate to the array you need to loop through.
The expression can be an array variable or method call that
returns an array.

public class Test


{
public static void main(String args[])
{
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers )
{
System.out.print( x ); System.out.print(",");
}
System.out.print("\n");
String [] names ={"James", "Larry", "Tom", "Lacy"};
for( String name : names )
{
System.out.print( name );
System.out.print(",");
}
}
}

-5-
BCA SEM 4 Prof. Aayushi Shah
JAVA PROGRAMMING

STRING AND STRINGBUFFER


Strings:
 A string is a sequence of characters.
 Java implements strings as objects of type String.
 Implementing strings as built-in objects make string handling convenient. As for
each basic operation on string, like string comparison, concatenation etc., it
provides built in methods.
 String objects can be constructed in a number of ways.
 String and StringBuffer classes are used to create string objects. These classes
are defined in java.lang package. So, they are available to all programs
automatically. Both are declared final, which means that they can not have
subclasses.
 Strings within objects of type String are unchangeable means that the contents of
the String instance cannot be changed after it has been created. But a variable
declared as a String reference can be changed to point at some other String
object at any time.

The java.lang.String class implements Serializable,Comparable and CharSequence interfaces.

-6-
BCA SEM 4 Prof. Aayushi Shah
JAVA PROGRAMMING
The CharSequence interface is used to represent the sequence of characters. String,StringBuffer
and StringBuilder classes implement it. It means, we can create strings in Java by using these
three classes. The Java String is immutable which means it cannot be changed. Whenever we
change any string, a new instance is created. For mutable strings, you can use StringBuffer and
StringBuilder classes.

Creation of String
There are two ways to create String object:
● By string literal
String s1 = "Hello DDU";
● By new keyword
String s1 = new String("Hello DDU");

String compare
We can compare string in java on the basis of content and reference.
● authentication (by equals() method)
● sorting (by compareTo() method)
● reference matching (by == operator)

compare by equals()
The String equals() method compares the original content of the string. It
compares values of string for equality. String class provides two methods:
public boolean equals(Object obj)
//compares this string to the specified object.
public boolean equalsIgnoreCase(String str)
//compares this String to another string, ignoring case.

compare by == operator
The = = operator compares references not values.
String s1="DDU";
String s2="DDU";
String s3=new String("DDU");
System.out.println(s1==s2); //true (because both refer to same instance)
System.out.println(s1==s3); //false(because s3 refers to instance created in
nonpool)

compare by compareTo()
The String compareTo() method compares values lexicographically
(alphabetical order.) and returns an integer value that describes if first
string is less than, equal to or greater than second string.
Suppose s1 and s2 are two string variables. If:
-7-
BCA SEM 4 Prof. Aayushi Shah
JAVA PROGRAMMING

● s1 == s2 :0
● s1 > s2 :positive value
● s1 < s2 :negative value

String Class Methods:


charAt(int) Returns the character at the specified index.
compareTo(String) Compares this String to another specified String.
concat(String) Concatenates the specified string to the end of this String.
copyValueOf(char[], int, int) Returns a String that is equivalent to the specified
character array.
copyValueOf(char[]) Returns a String that is equivalent to the specified character
array.
endsWith(String) Determines whether the String ends with some suffix.
equals(Object) Compares this String to the specified object.
equalsIgnoreCase(String) Compares this String to another object.
getChars(int, int, char[], int) Copies characters from this String into the specified
character array.
indexOf(String) Returns the index within this String of the first occurrence of the
specified substring.
indexOf(String, int) Returns the index within this String of the first occurrence of
the specified substring.
lastIndexOf(int, int) Returns the index within this String of the last occurrence of
the specified character.
lastIndexOf(String) Returns the index within this String of the last occurrence of
the specified substring.
length() Returns the length of the String.
replace(char, char) Converts this String by replacing all occurences of oldChar
with newChar.
startsWith(String) Determines whether this String starts with some prefix.
toCharArray() Converts this String to a character array.
toLowerCase() Converts all of the characters in this String to lower case.
toString() Converts this String to a String.
toUpperCase() Converts all of the characters in this String to upper case.
trim() Trims leading and trailing whitespace from this String.
valueOf(Object) Returns a String that represents the String value of the object.

-8-
BCA SEM 4 Prof. Aayushi Shah
JAVA PROGRAMMING

Wrapper Classes:
◈ Wrapper class in java provides the mechanism to convert primitive into object
and object into primitive.
◈ Since J2SE 5.0, autoboxing and unboxing feature converts primitive into
object and object into primitive automatically.
◈ The automatic conversion of primitive into object is known as autoboxing and
vice-versa unboxing.
◈ Why we need Wrapper Class?
◈ Wrapper Class will convert primitive data types into objects. The objects are
necessary if we wish to modify the arguments passed into the method (because
primitive types are passed by value).

The list of eight wrapper classes are given below:

Wrapper Class hierarchy:

-9-
BCA SEM 4 Prof. Aayushi Shah
JAVA PROGRAMMING

Wrapper class Example: Primitive to Wrapper

public class WrapperExample1{


public static void main(String args[]){
//Converting int into Integer
int a=20;
Integer i=Integer.valueOf (a); //converting int into Integer
//autoboxing, now compiler will write Integer.valueOf
//(a) internally
Integer j=a;
System.out.println (a+" "+i+" "+j);
}
}

Wrapper class Example: Wrapper to Primitive:

public class WrapperExample2{


public static void main(String args[]){
//Converting Integer to int
Integer a=new Integer(3);
int i=a.intValue();//converting Integer to int
//unboxing, now compiler will write a.intValue() internally
int j=a;
System.out.println(a+" "+i+" "+j);
- 10 -
BCA SEM 4 Prof. Aayushi Shah
JAVA PROGRAMMING

}
}
Wrapper and Primitive
Wrapper class provides a mechanism to convert primitive type into object and
object into primitive type.
A primitive type is a predefined data type provided by Java.
A Wrapper class is used to create an object; therefore, it has a corresponding
class.
A Primitive type is not an object so it does not belong to a class.
Required memory is higher than the primitive types.
Required memory is lower comparing to wrapper classes.

- 11 -
BCA SEM 4 Prof. Aayushi Shah
JAVA PROGRAMMING

Utility Classes:
Collection Overview:
The Collection in Java is a framework that provides an architecture to store and manipulate
the group of objects.
• Java Collection means a single unit of objects. Java Collection framework provides many
interfaces (Set,List, Queue) and classes (ArrayList, LinkedList , LinkedHashSet, TreeSet).

StringTokenizer:

The java.util.StringTokenizer class allows you to break a String into tokens. It


is simple way to break a String.
In the StringTokenizer class, the delimiters can be provided at the time of
creation or one by one to the tokens.

- 12 -
BCA SEM 4 Prof. Aayushi Shah
JAVA PROGRAMMING

import java.util.*;
public class Test {
public static void main(String[] args) {
StringTokenizer st = new StringTokenizer("my,name,is,Sem4");
// printing next token
System.out.println("Next token is : " + st.nextToken(","));
}
}

Calendar Class

The Calendar class is part of the java.util package and is used to work with dates
and times. It allows you to retrieve and manipulate various components of a
date/time such as year, month, day, hour, minute, second, etc.

Key Features:

 Provides methods to get and set date/time fields.


 Handles time zones and locale-specific information.
 Can perform date calculations, such as adding days or months to a date.

- 13 -
BCA SEM 4 Prof. Aayushi Shah
JAVA PROGRAMMING
import java.util.Calendar;

class CalendarExample {

public static void main(String[] args) {

// Get an instance of the Calendar

Calendar cal = Calendar.getInstance();

// Display current date and time

System.out.println("Current Date and Time: " + cal.getTime());

// Get individual components of the date

int year = cal.get(Calendar.YEAR);

int month = cal.get(Calendar.MONTH) + 1; // Months are 0-based

int day = cal.get(Calendar.DAY_OF_MONTH);

int hour = cal.get(Calendar.HOUR_OF_DAY);

int minute = cal.get(Calendar.MINUTE);

int second = cal.get(Calendar.SECOND);

System.out.println("Year: " + year);

System.out.println("Month: " + month);

System.out.println("Day: " + day);

System.out.println("Hour: " + hour);

System.out.println("Minute: " + minute);

System.out.println("Second: " + second);

// Add 7 days to the current date

cal.add(Calendar.DAY_OF_MONTH, 7);

System.out.println("Date after 7 days: " + cal.getTime());

- 14 -
BCA SEM 4 Prof. Aayushi Shah
JAVA PROGRAMMING

Iterator interface

 Iterator interface provides the facility of iterating the elements in a forward direction
only.

Iterable Interface

 The Iterable interface is the root interface for all the collection classes.
 The Collection interface extends the Iterable interface and therefore all the subclasses
of Collection interface also implement the Iterable interface.
 It contains only one abstract method.
 i.e., Iterator iterator()
 It returns the iterator over the elements of type T.

Random Class

The Random class is part of the java.util package and is used to generate random
numbers. It provides methods for generating random integers, floating-point
numbers, and other types.

Key Features:

 You can generate random numbers of different types (int, long, float,
double, boolean).
 Allows the creation of pseudo-random numbers based on an optional seed
for reproducibility.
import java.util.Random;

- 15 -
BCA SEM 4 Prof. Aayushi Shah
JAVA PROGRAMMING
class RandomExample {

public static void main(String[] args) {

// Create an instance of Random

Random random = new Random();

// Generate random numbers

int randomInt = random.nextInt(100); // Random integer between 0 and 99

double randomDouble = random.nextDouble(); // Random double between 0.0 and 1.0

boolean randomBoolean = random.nextBoolean(); // Random boolean (true/false)

System.out.println("Random Integer: " + randomInt);

System.out.println("Random Double: " + randomDouble);

System.out.println("Random Boolean: " + randomBoolean);

- 16 -
BCA SEM 4 Prof. Aayushi Shah
JAVA PROGRAMMING

Java ArrayList

 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 the java.util package.
 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 important points about the Java ArrayList class are:
 Java ArrayList class can contain duplicate elements.
 Java ArrayList class maintains insertion order.
 Java ArrayList class is non synchronized.
 Java ArrayList allows random access because the array works on an index basis.
 In ArrayList, manipulation is a little bit slower than the LinkedList in Java because a
lot of shifting needs to occur if any element is removed from the array list.
 We can not create an array list of the primitive types, such as int, float, char, etc.
 It is required to use the required wrapper class in such cases. For example:
 ArrayList al = ArrayList(); // does not work
 ArrayList al = new ArrayList(); // works fine

- 17 -
BCA SEM 4 Prof. Aayushi Shah
JAVA PROGRAMMING

import java.util.*;
public class ArrayListExam {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<String> list = new ArrayList<String>();
list.add("Mango");
list.add("Apple");
list.add("Banana");
list.add("Graphes");
System.out.println(list);
}
}
----------------------------------------------------------------------------
import java.util.*;
public class ArrayListExam {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<String> list = new ArrayList<String>();
list.add("Mango");
list.add("Apple");
list.add("Banana");
list.add("Graphes");
Iterator itr = list.iterator();
while(itr.hasNext()) {
System.out.println(itr.next());
}
}
}
- 18 -

You might also like