0% found this document useful (0 votes)
26 views24 pages

Union Sheet Class 8

This document covers fundamental concepts of arrays and strings in Java, including the definition, types, and operations on arrays, as well as the String class and its methods. It also explains the StringBuffer and StringBuilder classes, highlighting their differences, and discusses command line arguments and wrapper classes for converting between primitive types and objects. Key examples and syntax for creating and manipulating these data structures are provided throughout.

Uploaded by

Aditya
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)
26 views24 pages

Union Sheet Class 8

This document covers fundamental concepts of arrays and strings in Java, including the definition, types, and operations on arrays, as well as the String class and its methods. It also explains the StringBuffer and StringBuilder classes, highlighting their differences, and discusses command line arguments and wrapper classes for converting between primitive types and objects. Key examples and syntax for creating and manipulating these data structures are provided throughout.

Uploaded by

Aditya
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

Unit-3

Array and String


Contents
• Basic Java Program
• Single and Multidimensional Array
• String class
• Operations on string
• StringBuffer class
• StringBuilder class
• Command line Argument
• Use of Wrapper Class
Basic Java Program
public class Demo
{
public static void main(String args[])
{
System.out.println(“Hello World");
}
}

• Save this File as ‘Demo.java’


• To Compile above program (use cmd/terminal): javac Demo.java
• To execute/run above program (use cmd/terminal): java Demo
• Output: Hello World
Array
• Array is a collection of similar type of elements which has contiguous memory location.
• Java array is an object which contains elements of a similar data type.
• It is a type of non-primitive datatype in java.
• Array in Java is index-based and index starts with 0.
• If size of array is ‘n’ then indices will be used from 0 to n-1.

• Advantages: Code Optimization, Random Access.


• Disadvantage: Size limit (It doesn't grow its size at runtime).
• Types of Array:
1. One-dimensional Array
2. Multi-dimensional Array
One-dimentional Array
• It is used to create a single row/column.
• Syntax:
1. datatype variable [] = new datatype[size];
2. datatype variable[]; or datatype[] variable; or datatype []variable;
variable = new datatype[size];

• Example:
int a[] = new int[5];//declaration and instantiation
a[0]=10;
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
Multi-dimentional Array
• It forms a matrix using row index and column index both.
• Syntax:
datatype variable [][] = new datatype [row-size]
• Example:
1. int[][] arr = new int[2][2]; //2 rows and 2 columns
arr[0][0]=1;
arr[0][1]=2;
arr[1][0]=3;
arr[1][1]=4;

2. int arr [][] = {{1,2},{3,4}};


String Class
• String is known as a sequence/array of characters.
• In Java, strings are objects and non-primitive datatypes.
• The Java platform provides the ‘String’ class to create and manipulate strings.
• Whenever it encounters a string literal in your code, the compiler creates a String object with its
value.
• As with any other object, you can create String objects by using the new keyword and a
constructor.
• For example:
1. char[] ch = {‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘W’, ‘o’, ‘r’, ‘l’, ‘d’};
String s = new String(ch);
2. String s = “HelloWorld”;
String Class
• String is known as a sequence/array of characters.
• In Java, strings are objects and non-primitive datatypes.
• The Java platform provides the ‘String’ class to create and manipulate strings.
• Whenever it encounters a string literal in your code, the compiler creates a String object with its
value.
• As with any other object, you can create String objects by using the new keyword and a
constructor, for example:
char[] ch = {‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘W’, ‘o’, ‘r’, ‘l’, ‘d’};
String s = new String(ch);
• Two ways to create a string in Java:
1. String Literal: String s1 = “Hello”;
2. Using ‘new’ Keyword: String s2 = new String(“Welcome”);
Why String is Immutable?
• Immutable simply means unmodifiable or unchangeable.
• Once a string object is created its data or state can’t be changed but a new string object is created.
• Example:

Example1: Example2:

String s1 = “Hello”; String s2 = “Hello”;


s1.concat(“ World”); s2 = s2.concat(“ World”);
System.out.println(s1); System.out.println(s2);

Output: Hello Output: Hello World

Here “Hello” is not changed but a new object Here, concatenation of two strings is
is created with “Hello World”. That is why a performed as it is overwritten in s2 object.
string is known as immutable.
Operations on String
• List of methods supported by String class:

Method Description Return Type


charAt() Returns the character at the specified index char
(position).
compareTo() Compares two strings lexicographically. int
compareToIgnoreCase() Compares two strings lexicographically, ignoring case int
differences.
concat() Appends a string to the end of another string. String
contains() Checks whether a string contains a sequence of boolean
characters.
copyValueOf() Returns a String that represents the characters of the String
character array.
Operations on String
Method Description Return Type
endsWith() Checks whether a string ends with the specified boolean
character(s).
equals() Checks whether a string ends with the specified boolean
character(s).
equalsIgnoreCase() Compares two strings, ignoring case considerations. boolean
indexOf() Returns the position of the first found occurrence of int
specified characters in a string.
isEmpty() Checks whether a string is empty or not. boolean
length() Returns the length of a specified string. int
replace() Searches a string for a specified value, and returns a String
new string where the specified values are replaced.
Operations on String
Method Description Return Type
split() Splits a string into an array of substrings. String[]
startsWith() Checks whether a string starts with specified boolean
characters.
substring() Returns a new string which is the substring of a String
specified string.
toString() Returns the value of a String object. String
toLowerCase() Converts a string to lower case letters. String
toUpperCase() Converts a string to upper case letters. String
trim() Removes whitespace from both ends of a string. String
valueOf() Returns the string representation of the specified value. String
StringBuffer Class
• A thread-safe, mutable sequence of characters.
• A string buffer is like a String, but can be modified.
• At any point in time it contains some particular sequence of characters, but the length and content
of the sequence can be changed through certain method calls.
• String buffers are safe for use by multiple threads.
• The methods are synchronized where necessary.
• The class hierarchy is as follows:
java.lang.Object
↳ java.lang.StringBuffer
• Syntax:
public final class StringBuffer extends Object implements Serializable, CharSequence {
}
StringBuffer Class
• Constructors of Java StringBuilder class:

1. StringBuffer(): Constructs a string buffer with no characters in it and an initial capacity of 16


characters.
2. StringBuffer(CharSequence seq): Constructs a string buffer that contains the same characters as
the specified CharSequence.
3. StringBuffer(int capacity): Constructs a string buffer with no characters in it and the specified
initial capacity.
4. StringBuffer(String str): Constructs a string buffer initialized to the contents of the specified
string.
StringBuilder Class
• StringBuilder in Java represents a mutable sequence of characters.
• The function of StringBuilder is very much similar to the StringBuffer class, as both of them
provide an alternative to String Class by making a mutable sequence of characters.
• StringBuilder is not thread-safe and high in performance compared to StringBuffer.
• The StringBuilder class provides no guarantee of synchronization whereas the StringBuffer class
does.
• Therefore, this class is designed for use as a drop-in replacement for StringBuffer in places where
the StringBuffer was being used by a single thread (as is generally the case).
• Where possible, it is recommended that this class be used in preference to StringBuffer as it will be
faster under most implementations.
• Instances of StringBuilder are not safe for use by multiple threads.
• If such synchronization is required then it is recommended that StringBuffer be used.
StringBuilder Class
• The class hierarchy is as follows:
java.lang.Object
↳ java.lang.StringBuilder
• Syntax:
public final class StringBuilder extends Object implements Serializable, CharSequence{
}
• Constructors of Java StringBuilder class:
1. StringBuilder(): Constructs a string builder with no characters and an initial capacity of 16
characters.
2. StringBuilder(int capacity): Constructs a string builder with no characters in it and an initial
capacity specified by the capacity argument.
3. StringBuilder(CharSequence seq): Constructs a string builder that contains the same characters
as the specified CharSequence.
4. StringBuilder(String str): Constructs a string builder initialized to the contents of the specified
string.
StringBuilder Class
• Example:
StringBuilder str = new StringBuilder();
str.append(“Java”);
StringBuilder str1 = new StringBuilder("Hello World");
Command Line Argument
• The java command-line argument is an argument/parameter that is passed at the time of running
the java program.
• The arguments passed from the console(screen) can be received in the java program and it can be
used as an input.
• We can pass any numbers of arguments from the command prompt.
• We need to pass the arguments as space-separated values.
• We can pass both strings and primitive data types as command-line arguments.
• These arguments convert into a string array and are provided to the main() function as a string
array argument.
• When command-line arguments are supplied to JVM, JVM wraps these and supplies them to
args[].
• It can be confirmed that they are wrapped up in an args array by checking the length of args using
args.length.
Command Line Argument
• Example:
class Demo {
public static void main(String[] args) {
for(int i=0; i<args.length; i++)
System.out.println(args[i]);
}
}
• Save file as ‘Demo.java’.
• Compile: javac Demo.java
• Run: java Demo Hello World
• Output: Hello World
Command Line Argument
 Passing Numeric Command-Line Arguments:
• For this, we can use parseX method (where X=Datatype) which converts string arguments into
numeric format.
• Example:
//Addition of 2 numbers using command line arguments
class Demo {
public static void main(String[] args) {
int a = Integer.parseInt(args[0]); Compile: javac Demo.java
Run: java Demo 10 20
int b = Integer.parseInt(args[1]); Output: 30
System.out.println(a+b);
}
}
Wrapper Class
• A Wrapper class in Java is a class that converts primitive datatypes into objects and objects into
primitive datatypes.
• The automatic conversion of primitive datatype into an object is called autoboxing.
• The conversion of object into a primitive datatype is called unboxing.

Autoboxing

Primitive Non Primitive


Datatype Datatype
(variable) (object)

Unboxing
Wrapper Class
• The 8 classes of the java.lang package are known as wrapper classes in Java.
• The list of 8 wrapper classes are given below:

Primitive Datatype Wrapper Class


boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
Wrapper Class
1) Autoboxing:
• The automatic conversion of primitive datatype into its corresponding wrapper class is called
autoboxing.
• For example, byte to Byte, char to Character, int to Integer, long to Long, float to Float, boolean to
Boolean, double to Double, and short to Short.
• Since Java 5, we do not need to use the valueOf() method of wrapper classes to convert the primitive
datatype into objects.

• Example:
//Converting int into Integer
int a = 20;
Integer i = Integer.valueOf(a); //converting int into Integer explicitly
or
Integer j = a; //autoboxing, now compiler will write Integer.valueOf(a) internally
Wrapper Class
2) Unboxing:
• The automatic conversion of wrapper type into its corresponding primitive datatype is called
unboxing.
• It is the reverse process of autoboxing.
• Since Java 5, we do not need to use the xValue() method of wrapper classes to convert the wrapper
type into primitives (here, x=datatype).
• Example:
//Converting Integer to int
Integer a = new Integer(3);
int i = a.intValue(); //converting Integer to int explicitly
or
int j = a; //unboxing, now compiler will write a.intValue() internally

You might also like