Java Api

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 45

USING

Selected classes from the Java API and


arrays, and Flow Control
Gopal Patidar
patidar.gopal27@gmail.com

Prof. Nilesh Gambhava


Computer Engineering Department,
Darshan Institute of Engineering & Technology, Rajkot
Topics Covered
USING
Introduction to JAVA API

Selected classes from the Java API and arrays


• Creating and manipulating String and StringBuilder objects
• Using common methods from classes String and StringBuilder
• Creating and using one-dimensional and multidimensional arrays
• Accessing elements in asymmetric multidimensional arrays
• Declaring, creating, and using an ArrayList
• Manipulating date objects using the class Period

Flow Control“
• Creating and using if, if-else, ternary, and switch constructs
• Creating and using loops: while, do-while, for, and enhanced for
• Creating nested constructs for selection and iteration statements
• Comparing the do-while, while, for, and enhanced for loop constructs
• Using break and continue statements
Prof. Nilesh Gambhava
Computer Engineering Department,
Darshan Institute of Engineering & Technology, Rajkot
Java API
Introduction to JAVA API(Application Programming Interface):

JDK is for development purpose whereas JRE is for running the java programs.
Introduction to JAVA API(Application Programming Interface):

JDK is for development purpose whereas JRE is for running the java programs.
Introduction to JAVA API(Application Programming Interface):

The Java API is a set of classes, interfaces, and methods provided by the Java

programming language for developers to use in their applications.

It covers a wide range of functionalities, including input/output, networking,

graphics, data structures, utilities, and much more.

When you refer to "Selected classes from the Java API," it could mean any classes

from this extensive set.


Introduction to JAVA API(Application Programming Interface):

Some commonly used packages and classes from the Java API include:

java.lang: Provides fundamental classes such as Object, String, and basic data types.

java.util: Offers collections (ArrayList, HashMap, etc.), date and time utilities, and other utility

classes.

java.io: Handles input and output operations, including file I/O.

java.net: Facilitates networking tasks.

When working with the Java API, developers can import these classes and use their methods to build

applications.
Introduction to JAVA API

Selected classes from the Java API and arrays


• Creating and manipulating String and StringBuilder objects
• Using common methods from classes String and StringBuilder
• Creating and using one-dimensional and multidimensional arrays
• Accessing elements in asymmetric multidimensional arrays
• Declaring, creating, and using an ArrayList
• Manipulating date objects using the class Period

Flow Control“
• Creating and using if, if-else, ternary, and switch constructs
• Creating and using loops: while, do-while, for, and enhanced for
• Creating nested constructs for selection and iteration statements
• Comparing the do-while, while, for, and enhanced for loop constructs
• Using break and continue statements
Creating and manipulating String and StringBuilder objects

In Java, the String class is used to represent sequences of characters, and it is immutable,
meaning once a String object is created, its content cannot be changed. On the other hand,
the StringBuilder class is mutable, allowing you to modify the content of the string without
creating a new object each time.

Creating String objects

String str1 = new String("Paul");


String str2 = new String("Paul");
System.out.println(str1 == str2);

a comparison of the String reference variables str1 and str2 prints false.
The operator == compares the addresses of the objects referred to by the variables str1 and
str2. Even though these String objects store the same sequence of characters, they refer to
separate objects stored at separate locations
String str3 = "Harry";
String str4 = "Harry";
System.out.println(str3 == str4);
// Creating a String
String str1 = "Harry";

// Concatenating Strings
String str2 = " Paul";
String result1 = str1 + str2; // Concatenation using the + operator

// Getting the length of a String


int length = str1.length();

// Accessing characters in a String


char firstChar = str1.charAt(0); // Gets the character at index 0

// Substring
String substring = str1.substring(7); // Extracts substring starting from index
7

// Comparing Strings
boolean isEqual = str1.equals("Hello, World!");

// Other String methods


String lowerCase = str1.toLowerCase();
String upperCase = str1.toUpperCase();
EXAM TIP

• The default value for String is null.


• If a String object is created using the keyword new, it always results in the
creation of a new String object. String objects created this way are never
pooled. When a variable is assigned a String literal using the assignment
operator, a new String object is created only if a String object with the
same value isn’t found in the String constant pool.
• The length of a String is one number greater than the position that stores
its last character. The length of String "Shreya" is 6, but its last character, a,
is stored at position 5 because the positions start at 0, not 1.
• The operator == compares whether the reference variables refer to the
same objects, and the method equals compares the String values for
equality. Always use the equals method to compare two Strings for
equality. Never use the == operator for this purpose.
The class StringBuilder is defined in the package java.lang, and it has a mutable sequence
of characters. You should use the class StringBuilder when you’re dealing with larger
strings or modifying the contents of a string often
difference between StringBuilder and String
1. Mutability:
•String:
•Strings in Java are immutable. Once a String object is created, its content cannot be changed.
•Any operation that appears to modify a String actually creates a new String object.
•StringBuilder:
•StringBuilder is mutable. You can modify the contents of a StringBuilder object without creating a new object.
•This makes StringBuilder more efficient when performing multiple modifications on a string.

2. Performance:
•String:
•Since strings are immutable, concatenating or modifying strings using the + operator or methods like concat() or substring()
creates new string objects.
•This can be inefficient in terms of memory and performance, especially when dealing with a large number of string modifications.
•StringBuilder:
•StringBuilder is more efficient for building and modifying strings because it allows in-place modifications.
•It avoids the creation of unnecessary intermediate string objects, making it faster and more memory-efficient when dealing with
concatenation or modifications.
Creating StringBuilder objects

class CreateStringBuilderObjects
{
public static void main(String args[])
{
StringBuilder sb1 = new StringBuilder //no characters in it and an initial capacity of 16 characters
StringBuilder sb2 = new StringBuilder(sb1); //same as sb1
StringBuilder sb3 = new StringBuilder(50); //object with no characters and an initial capacity of 50 characters.

StringBuilder sb4 = new StringBuilder("Shreya Gupta"); //object sb4 with the value Shreya Gupta.

}
}
public class Main{ public static void main(String[] args)
{
// Creating a StringBuilderStringBuilder stringBuilder = new StringBuilder("Hello");
System.out.println(stringBuilder);

// Appending to StringBuilderstringBuilder.append(", World!");


// Appends ", World!" to the StringBuilder
System.out.println(stringBuilder);
// Inserting into StringBuilderstringBuilder.insert(5, " Java"); // Inserts " Java" at index
5System.out.println(stringBuilder);// Deleting from StringBuilderstringBuilder.delete(0, 5); //
Deletes characters from index 0 to 4System.out.println(stringBuilder);// Updating characters
in StringBuilderstringBuilder.setCharAt(0, 'h'); // Sets the character at index 0 to
'h'System.out.println(stringBuilder);// Converting StringBuilder to StringString result2 =
stringBuilder.toString();System.out.println(result2);// Other StringBuilder methodsint length2
= stringBuilder.length();System.out.println(length2);int capacity =
stringBuilder.capacity();System.out.println(capacity); }}
EXAM TIP
• Combinations of the deleteCharAt and insert methods can be quite
confusing
• You can’t use the method reverse to reverse a substring of StringBuilder.
Arrays
Declare, instantiate, initialize, and use a one-dimensional array
Declare, instantiate, initialize, and use a multidimensional array
Need of Array Variable
 Suppose we need to store rollno of the student in the integer variable.
Declaration
int rollno;
 Now we need to store rollno of 100 students.
Declaration
int rollno101, rollno102, rollno103, rollno104...;
 This is not appropriate to declare these many integer variables.
e.g. 100 integer variables for rollno.
 Solution to declare and store multiple variables of similar type is an array.
 An array is a variable that can store multiple values.
Definition: Array
 An array is a fixed size sequential collection of elements of same data type grouped
under single variable name.

[0] [1] [2] … [99]

int rollno[];
rollno = new int[100]

Fixed Size Sequential Same Data type Single Name


Here, the size of an It is indexed to 0 to 99 All the elements (0-99) All the elements (0-99)
array is 100 (fixed) to in sequence will be integer will be referred as a
store rollno variables common name rollno
Declaring an array
Syntax  By default array index starts
data-type variable-name[size]; with 0.
 If we declare an array of size
5 then its index ranges from
Integer Array [0] [1] [2] [3] [4] 0 to 4.
 First element will be store at
int mark[]; mark[0] and last element
mark = new int[5] integer will be stored at mark[4] not
mark[5].
[0] [1] [2] [3] [4]  Like integer and float array
Float Array
we can declare array of type
float mark[]; char.
mark = new float[5]
float
Arrays can store two types of data:
A collection of primitive data types
A collection of objects
class CreateArray
{
public static void main(String args[])
{
int intArray[] = new int[] {4, 8, 107}; //Array of primitive data

String objArray[] = new String[] {"Harry", "Shreya", "Paul", "Selvan"}; //Array of objects

}
}
Types of Array
Creating an array involves three steps, as follows:
• Declaring the array
• Allocating the array
• Initializing the array elements
public class ArrayExample {

public static void main(String[] args) {


// Declare an array of integers
int[] numbers;

// Instantiate the array with a specific size


numbers = new int[5];

// Initialize the array elements


numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
ArrayList

ArrayList is one of the most widely used classes from the Collections
framework. It offers the best combination of features offered by an array
and the List data structure. The most commonly used operations with a list
are add items to a list, modify items in a list, delete items from a list, and
iterate over the items.
Flow control
I’ll cover the following topics in this chapter:
 Creating and using if, if-else, ternary, and switch constructs to execute statements
selectively
 Creating and using loops: while, do-while, for, and enhanced for
 Creating nested constructs for selection and iteration statements
 Comparing the do-while, while, for, and enhanced for loop constructs
 Using break and continue statements
The if construct and its flavors
 An if construct enables you to execute a set of statements in your code based on
the result of a condition. This condition must always evaluate to a boolean or a
Boolean value. You can specify a set of statements to execute when this condition
evaluates to true or

Multiple flavors of the if statement are illustrated in figure


 if
 if-else
 if-else-if-else false.
int score = 100;
String result = "";
String name = "Lion";
Ternary construct
 You can use a ternary operator, ? : , to define a ternary construct. A ternary
construct can be compared to a compact if-else construct, used to assign a value to
a variable depending on a boolean expression.
 In the following example, the variable discount is assigned the value 15 if the
expression (bill > 2000) evaluates to true but 10 otherwise:
The switch statement
 You can use a switch statement to compare the value of a variable with multiple
values. For each of these values, you can define a set of statements to execute. The
following example uses a switch statement to compare the value of the variable
marks with the literal values 10, 20, and 30, defined using the case keyword:
What is loop?
 Loop is used to execute the block of code several times according to the condition
given in the loop. It means it executes the same code multiple times.

“Hello” 5

Output
System.out.println("Hello\n");
Hello
System.out.println("Hello\n"); loop(condition)
Hello {
System.out.println("Hello\n"); //statements
Hello
System.out.println("Hello\n"); }
Hello
System.out.println("Hello\n");
Hello
if v/s while

Flowchart of if v/s Flowchart of while

False False
condition condition

True True

… …
Looping or Iterative Statements
Looping Statements are
Entry Controlled Loop: while, for
Exit Controlled Loop: do…while
Virtual Loop: goto

While loop
While Loop
 while is an entry controlled loop
 Statements inside the body of while are repeatedly executed till the condition is
true
 while is keyword
Syntax
while(condition)
{
// Body of the while
// true part
}

for loop
for Loop
 for is an entry controlled loop
 Statements inside the body of for are repeatedly executed till the condition is true
 for is keyword
Syntax
for (initialization; condition; updateStatement)
{
// statements
}

 The initialization statement is executed only once.


 Then, the condition is evaluated. If the condition is false, the for loop is
terminated.
 If the condition is true, statements inside the body of for loop are executed, and
the update statement is updated.
 Again the condition is evaluated.

do while loop
do while Loop
 do while is an exit controlled loop.
 Statements inside the body of do while are repeatedly executed till the condition
is true.
 Do and while are keywords. Syntax
do
{
// statement
}
while (condition);

 Loop body will be executed first, and then condition is checked.


 If the condition is true, the body of the loop is executed again and the condition is
evaluated.
 This process goes on until the condition becomes false.
 If the condition is false, the loop ends.

goto statement
goto Statement
 goto is an virtual loop
 The goto statement allows us to transfer control of the program to the specified
label.
 goto is keyword
Syntax Syntax
goto label; label:
. .
. .
. .
label: goto label;

 The label is an identifier. When the goto statement is encountered, the control of
the program jumps to label: and starts executing the code.

Thank you

patidar.gopal27@gmail.com

You might also like