0% found this document useful (0 votes)
3 views

OOP-Lecture 2

The document covers control structures in Java, including conditional statements (if, if-else, switch), loops (while, do-while, for), and array handling (single and multidimensional arrays). It also discusses the String class and its methods, emphasizing immutability, the String pool, and various operations like concatenation and substring extraction. Additionally, the StringBuffer class is introduced as a mutable alternative to String, along with its methods for string manipulation.

Uploaded by

Kartik Bhatia
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

OOP-Lecture 2

The document covers control structures in Java, including conditional statements (if, if-else, switch), loops (while, do-while, for), and array handling (single and multidimensional arrays). It also discusses the String class and its methods, emphasizing immutability, the String pool, and various operations like concatenation and substring extraction. Additionally, the StringBuffer class is introduced as a mutable alternative to String, along with its methods for string manipulation.

Uploaded by

Kartik Bhatia
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Lecture 2

Unit 1
Control Structures
● If
● If else
● If else if
● while
● do while
● for
● for each
● switch
● Break & Continue Statement
if
int x = 10;
int y = 12;
if(x+y > 20) {
System.out.println("x + y is greater than 20");
}
if-else
int x = 10;
int y = 12;
if(x+y < 10) {
System.out.println("x + y is less than 10");
}else {
System.out.println("x + y is greater than 20");
}
if-else-if
String city = "Delhi";
if(city == "Meerut") {
System.out.println("city is meerut");
}else if (city == "Noida") {
System.out.println("city is noida");
}else if(city == "Agra") {
System.out.println("city is agra");
}else {
System.out.println(city);
}
while
int i = 0;
while(i<=10) {
System.out.println(i);
i = i + 2;
}
do while
int i = 0;
do {
System.out.println(i);
i = i + 2;
}while(i<=10);
for
int sum = 0;

for(int j = 1; j<=10; j++) {

sum = sum + j;

System.out.println("The sum of first 10 natural numbers is "


+ sum);
for each
String[] names = {"Java","C","C++","Python","JavaScript"};

for(String name:names) {

System.out.println(name);

}
switch
int num = 2;
switch (num){
case 0:
System.out.println("number is 0");
break;
case 1:
System.out.println("number is 1");
break;
default:
System.out.println(num);
}
break
for (int i = 0; i < 10; i++) {
// Terminate the loop when i is 5
if (i == 5)
break;
System.out.println("i: " + i);
}
continue
for (int i = 0; i < 10; i++) {
// If the number is even
// skip and continue
if (i % 2 == 0)
Continue;
// If number is odd, print it
System.out.print(i + " ");
}
Arrays
An array is typically a grouping of elements of the same kind that are stored in a
single, contiguous block of memory.
There are two types of array.
○ Single Dimensional Array
○ Multidimensional Array
Instantiation of an Array in Java
arrayRefVar = new datatype[size];
Examples
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
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]);
Examples Cont…
int a[]={33,3,4,5};//declaration, instantiation and
initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of
array
System.out.println(a[i]);
Examples Cont… (2D arrays)
int arr[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; // 3x3
matrix
// Printing the 2D array
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
Examples Cont… (Jagged arrays)
int arr[][] = new int[3][];
arr[0] = new int[3];
arr[1] = new int[4];
arr[2] = new int[2];
//initializing a jagged array
int count = 0;
for (int i=0; i<arr.length; i++)
for(int j=0; j<arr[i].length; j++)
arr[i][j] = count++;

//printing the data of a jagged array


for (int i=0; i<arr.length; i++){
for (int j=0; j<arr[i].length; j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();//new line
}
Examples Cont… Copying a Java Array
public static void arraycopy(Object source_arr, int sourcePos,
Object dest_arr, int destPos, int len)
Parameters :
source_arr : array to be copied from
sourcePos : starting position in source array from where to copy
dest_arr : array to be copied in
destPos : starting position in destination array, where to copy in
len : total no. of components to be copied.

char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e', 'i', 'n',
'a', 't', 'e', 'd' };
char[] copyTo = new char[7];
System.arraycopy(copyFrom, 2, copyTo, 0, 7);
System.out.println(String.valueOf(copyTo));//caffein
String Class
● In Java, string is basically an object that represents sequence of char values. An array of characters
works same as Java string. For example:
char[] ch={'j','a','v','a','p','r','o','g','r','a','m'};

String s=new String(ch);

// 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(), substring() etc.
String Class Cont…
The String class is one of the most fundamental types in Java, designed to represent immutable sequences of characters.
Here's a closer look at its characteristics and the interfaces it implements:

○ Immutability: Once instantiated, a String object cannot be modified. This immutable design is a deliberate choice to
ensure thread safety, consistency, and efficiency, especially regarding the String pool mechanism.
○ String Pool: Java maintains a pool of string literals to help save memory. When a new string literal is created, Java
checks the Pool for a matching string. If found, the new variable references the pooled string. If not, the new string is
added to the Pool.
○ Implemented Interfaces: The String class implements several interfaces, including:
○ Serializable: Allows string objects to be serialized into byte streams, facilitating their transmission or storage.
○ Comparable<String>: Enables lexical comparison between two strings, supporting natural ordering within
collections.
○ CharSequence: Provides a unified read-only interface for different kinds of char sequences, allowing String
objects to be manipulated and accessed generically.
Some Methods of String Class
● char charAt(int index)
● int compareTo(String anotherString)
● String concat(String str)
● boolean contains(CharSequence s)
● boolean equals(Object anObject)
● int length()
● String replace(char oldChar, char newChar)
● String[] split(String regex)
● String substring(int beginIndex, int endIndex)
● String toUpperCase()
● String trim()

Full list: https://www.w3schools.com/java/java_ref_string.asp


Examples
charAt: The charAt() method returns the character at the specified index in a string.

String myStr = "Hello";

char result = myStr.charAt(0);

System.out.println(result);

Output: H
compareTo: The method returns 0 if the string is equal to the other string. A value less than 0 is returned if the
string is less than the other string (less characters) and a value greater than 0 if the string is greater than the
other string (more characters).
String myStr1 = "Hello";

String myStr2 = "Hello";

System.out.println(myStr1.compareTo(myStr2));

Output: 0
Examples Cont…
concat: The concat() method appends (concatenate) a string to the end of another string.

String firstName = "John ";


String lastName = "Doe";
System.out.println(firstName.concat(lastName));
Output: John Doe
contains: The contains() method checks whether a string contains a sequence of characters.

Returns true if the characters exist and false if not.

String myStr = "Hello";

System.out.println(myStr.contains("Hel")); // true

System.out.println(myStr.contains("Hi")); // false
Examples Cont…
length: The length() method returns the length of a specified string.

String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

System.out.println(txt.length());

Output: 26

substring: Returns a new string which is the substring of a specified string.

String myStr = "Hello, World!";

System.out.println(myStr.substring(7, 12));

Output: World
Manipulating Characters in a String
Use to manipulate characters in string:
● replace
● replaceAll
● replaceFirst

Example replace:
String myStr = "Hello";

System.out.println(myStr.replace('l', 'p'));

Output: Heppo
StringBuffer Class
Java StringBuffer class is used to create mutable (modifiable) String objects. The StringBuffer
class in Java is the same as String class except it is mutable i.e. it can be changed.

StringBuffer() It creates an empty String buffer with the initial capacity of 16.
StringBuffer(String str) It creates a String buffer with the specified string..
StringBuffer(int capacity) It creates an empty String buffer with the specified capacity as length
Some Methods of StringBuffer Class
● append
● insert
● replace
● reverse
● substring
Examples
The append() method concatenates the given argument with this String.
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
The insert() method inserts the given String with this string at the given position.
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
Examples Cont…
The replace() method replaces the given String from the specified beginIndex and endIndex.
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
The reverse() method of the StringBuilder class reverses the current String.
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
Examples Cont…
The replace() method replaces the given String from the specified beginIndex and
endIndex.

StringBuffer str = new StringBuffer("Hello World");

// get substring start from index 5 to index 8

System.out.println("SubSequence = " + str.substring(5, 8));


// Wo

You might also like