0% found this document useful (0 votes)
14 views46 pages

Module 2 PP2

J

Uploaded by

Ezhilin Freeda
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views46 pages

Module 2 PP2

J

Uploaded by

Ezhilin Freeda
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Module 2

Structure of Java Program


Documentation Section

• The documentation section is an important section but optional for a Java program.
• It includes basic information about a Java program. The information includes the author's name,
date of creation, version, program name, company name, and description of the program.
• It improves the readability of the program. Whatever we write in the documentation section, the
Java compiler ignores the statements during the execution of the program
• Single-line Comment: It starts with a pair of forwarding slash (//). For example:
//First Java Program
• Multi-line Comment: It starts with a /* and ends with */. We write between these two symbols. For
example:
/*It is an example of
multiline comment*/
Documentation Comment: It starts with the delimiter (/**) and ends with */. For example:
Package Declaration

• The package declaration is optional. It is placed just after the documentation


section.
• In this section, we declare the package name in which the class is placed. Note
that there can be only one package statement in a Java program.
• It must be defined before any class and interface declaration. It is necessary
because a Java class can be placed in different packages and directories based on
the module they are used.
• For all these classes package belongs to a single parent directory. We use the
keyword package to declare the package name.
For example:package com.example.myapp;
Import Statements

• The package contains the many predefined classes and interfaces. If we


want to use any class of a particular package, we need to import that class.
• The import statement represents the class stored in the other package.
• We use the import keyword to import the class. It is written before the class
declaration and after the package statement.
• We use the import statement in two ways, either import a specific class or
import all classes of a particular package.
In a Java program, we can use multiple import statements. For example:
import java.util.Scanner; //it imports the Scanner class only
import java.util.*; //it imports all the class of the java.util package
Interface Section

• It is an optional section.
• We can create an interface in this section if required.
• We use the interface keyword to create an interface.
• An interface is a slightly different from the class.
• It contains only constants and method declarations.
• Another difference is that it cannot be instantiated.
• We can use interface in classes by using the implements keyword.
• An interface can also be used with other interfaces by using the extends keyword. For example:
interface car
{
void start();
void stop();
}
Class Definition

• In this section, we define the class. It is vital part of a Java program. Without the
class, we cannot create any Java program.
• A Java program may conation more than one class definition. We use
the class keyword to define the class.
• The class is a blueprint of a Java program. It contains information about user-
defined methods, variables, and constants.
• Every Java program has at least one class that contains the main() method. For
example:
class Student //class definition
{
}
Class Variables and Constants
In this section, we define variables and constants that are to be used later in the program.
In a Java program, the variables and constants are defined just after the class definition.
The variables and constants store values of the parameters.
It is used during the execution of the program. We can also decide and define the scope of
variables by using the modifiers. It defines the life of the variables. For example:
class Student //class definition
{
String sname; //variable
int id;
double percentage;
}
Main Method Class

• In this section, we define the main() method. It is essential for all Java programs.
• Because the execution of all Java programs starts from the main() method. In other words,
it is an entry point of the class.
• It must be inside the class. Inside the main method, we create objects and call the
methods. We use the following statement to define the main() method:

public static void main(String args[])


{
}
What is an Array in Java?

• An array in Java is a collection of elements of the same type stored


in a contiguous memory location.It allows us to store multiple values
in a single variable instead of declaring multiple variables.
• Types of Arrays in Java
• Single-dimensional array → A list of elements in a single row/line.
• Multi-dimensional array → Arrays within arrays (like a matrix).
Syntax
• Declaration
datatype[] arrayName; // Preferred
Datatype arrayName[]; // Also valid
• Creation
arrayName = new datatype[size];
• Initialization
arrayName[index] = value;
Single Dimensional Array
public class ArrayExample { numbers[4] = 50;
public static void main(String[] args) {
// Declare and create array // Display elements
int[] numbers = new int[5]; System.out.println("Array Elements:");
for (int i = 0; i < numbers.length; i++) {
// Initialize elements System.out.println("Index " + i + ": "
numbers[0] = 10; + numbers[i]);
numbers[1] = 20; }
numbers[2] = 30; }
numbers[3] = 40; }
Example – 2D Array
public class TwoDArrayExample { for (int i = 0; i < matrix.length; i++) {
public static void main(String[] args) { for (int j = 0; j < matrix[i].length; j+
// Create 2D array (matrix) +) {
int[][] matrix = { System.out.print(matrix[i][j] + "
");
{1, 2, 3},
}
{4, 5, 6},
System.out.println();
{7, 8, 9}
}
};
}
}
// Print matrix
What is a String in Java?

• A String in Java is a sequence of characters.


• In Java, strings are objects of the String class, not primitive data types.
• They are immutable, meaning once created, their value cannot be
changed.
Creating Strings

• There are two main ways to create strings:


(i) Using String Literal
String str1 = "Hello";
• String str1 = "Hello";
String str2 = "Hello";
Using new Keyword

• The string can also be declared using a new operator i.e. dynamically
allocated.
• In case of String are dynamically allocated they are assigned a new
memory location in the heap .
• This string will not be added to the String constant pool.
String str1 = new String("John");
String str2 = new String("Deo");
Example
Class Example String s3 = new String("TAT");
{ String s4 = new String("TAT");
public static void main(String args[])
{ // Printing all the Strings
System.out.println(s1);
// Declaring Strings using String System.out.println(s2);
literals System.out.println(s3);
String s1 = "TAT"; System.out.println(s4);
String s2 = "TAT"; }
}
// Declaring Strings using new keyword
Concatenating String

There are 2 methods to concatenate two or more string.

 Using concat() method


 Using + operator
Using concat() method public class Demo{
public static void main(String[] args)
Concat() method is used to add two or more string {
into a single string object. It is string class method String s = "Hello";
and returns a string object. String str = "Java";
String str1 = s.concat(str);
System.out.println(str1);
}
}
Output:
HelloJava
Using + operator
Java uses "+" operator to concatenate two string objects into single one. It can also concatenate
numeric value with string object.

public class Demo{


public static void main(String[] args)
{
String s = "Hello";
String str = "Java";
String str1 = s+str;
String str2 = "Java"+11;
System.out.println(str1);
System.out.println(str2);
} Output:
} HelloJava
Java11
String Comparison
To compare string objects, Java provides methods and operators both. So we can
compare string in following three ways.

 Using equals() method


 Using == operator
 By CompareTo() method

Using equals() method


equals() method compares two strings for equality. Its general syntax is,

boolean equals (Object str)


Example
It compares the content of the strings. It will return true if string matches, else
returns false.

public class Demo{


public static void main(String[] args) {
String s = "Hell";
String s1 = "Hello";
String s2 = "Hello";
boolean b = s1.equals(s2); //true
System.out.println(b);
b = s.equals(s1) ; //false
System.out.println(b);
} Output:
} true
false
Using == operator
The double equal (==) operator compares two object references to check whether they refer
to same instance. This also, will return true on successful match else returns false.

public class Demo{


public static void main(String[] args) {
String s1 = "Java";
String s2 = "Java";
String s3 = new String ("Java");
boolean b = (s1 == s2); //true
System.out.println(b);
b= (s1 == s3); //false
System.out.println(b);
}
}
Output:
true
false
By compareTo() method

The String compareTo() method compares values lexicographically 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:
 s1 == s2 :0
 s1 > s2 :positive value
 s1 < s2 :negative value

class Teststringcomparison4{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
System.out.println(s1.compareTo(s2));//0
System.out.println(s1.compareTo(s3));//1(because s1>s3)
System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
} }
Substring in Java

A part of string is called substring. In other words, substring is a subset of another


string. In case of substring startIndex is inclusive and endIndex is exclusive.

public String substring(int startIndex): This method returns new String object
containing the substring of the given string from specified startIndex (inclusive).
public String substring(int startIndex, int endIndex): This method returns new
String object containing the substring of the given string from specified startIndex to
endIndex.

startIndex: inclusive
endIndex: exclusive
startIndex and endIndex
String s="hello";
System.out.println(s.substring(0,2));

In the above substring, 0 points to h but 2 points to e (because end index is exclusive).

Example

public class TestSubstring{


public static void main(String args[]){ Output:
String s="SachinTendulkar"; Tendulkar
System.out.println(s.substring(6));//Tendulkar Sachin
System.out.println(s.substring(0,6));//Sachin
}
}
Java String class methods
• The java.lang.String class provides a lot of methods to work on string.
By the help of these methods, we can perform operations on string
such as trimming, concatenating, converting, comparing, replacing
strings etc.

• Java String is a powerful concept because everything is treated as a


string if you submit any form in window based, web based or mobile
application.
Java String toUpperCase() and
toLowerCase() method
String s="Sachin";
System.out.println(s.toUpperCase());//SACHIN
System.out.println(s.toLowerCase());//sachin
System.out.println(s);//Sachin(no change in original)
SACHIN
sachin
Sachin
Java String trim() method

The string trim() method eliminates white spaces before and


after string.

String s=" Sachin ";


Sachin
System.out.println(s);// Sachin Sachin

System.out.println(s.trim());//Sachin
Java String startsWith() and
endsWith() method
public class Testmethodofstringclass2{
public static void main(String args[]){

String s="Sachin";
true
System.out.println(s.startsWith("Sa"));//true true

System.out.println(s.endsWith("n"));//true
}
}
Java String charAt() method
• The string charAt() method returns a character at specified index.
public class Testmethodofstringclass3{
public static void main(String args[]){

String s="Sachin"; S
System.out.println(s.charAt(0));//S h

System.out.println(s.charAt(3));//h
}
}
Java String length() method
public class Testmethodofstringclass4{
public static void main(String args[]){

String s="Sachin";
System.out.println(s.length());//6
} 6

}
Java String valueOf() method
• The string valueOf() method coverts given type such as int, long, float,
double, boolean, char and char array into string.
int a=10;
String s=String.valueOf(a);
System.out.println(s+10);
Output:

1010
Java String replace() method
• The string replace() method replaces all occurrence of first sequence of
character with second sequence of character.

String s1="Java is a programming language. Java is a platform. Java is an Island.";


String replaceString=s1.replace("Java","Kava");//replaces all occurrences of "Java"
to "Kava"
System.out.println(replaceString);
• Output:

• Kava is a programming language. Kava is a platform. Kava is an Island.


StringBuffer class in Java
• StringBuffer class is used to create a mutable string object. It means, it can be
changed after it is created. It represents growable and writable character sequence.
• It is similar to String class in Java both are used to create string, but stringbuffer
object can be changed.
• So StringBuffer class is used when we have to make lot of modifications to our
string. It is also thread safe i.e multiple threads cannot access it simultaneously.
StringBuffer defines 4 constructors.
• StringBuffer(): It creates an empty string buffer and reserves space for 16 characters.
• StringBuffer(int size): It creates an empty string and takes an integer argument to set capacity
of the buffer.
• StringBuffer(String str): It creates a stringbuffer object from the specified string.
• StringBuffer(charSequence []ch): It creates a stringbuffer object from the charsequence array.
Creating a StringBuffer Object
public class Demo {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("study");
study
System.out.println(sb); studytonight
// modifying object
sb.append("tonight");
System.out.println(sb); // Output: studytonight

}
}
Difference between String and
StringBuffer
class Test {
public static void main(String args[])
{
String str = "study"; Study
str.concat("tonight"); studytonight
System.out.println(str); // Output: study

StringBuffer strB = new StringBuffer("study");


strB.append("tonight");
System.out.println(strB); // Output: studytonight
}
• }
Important methods of StringBuffer
class
• length(): Returns the StringBuffer object’s length.
• capacity(): Returns the capacity of the StringBuffer object.
Example
public class StringBufferExample {

public static void main(String[] args) {


StringBuffer sb = new StringBuffer("Hello");
int sbLength = sb.length();
int sbCapacity = sb.capacity();
System.out.println("String Length of " + sb + " is " + sbLength);
System.out.println("Capacity of " + sb + " is " + sbCapacity);
string Length of Hello is 5
} Capacity of Hello is 21

}
append():
• It appends the specified argument string representation at the end of
the existing String Buffer. This method is overloaded for all the
primitive data types and Object.
StringBuffer sb = new StringBuffer("Hello ");
sb.append("World ");
sb.append(2017);
System.out.println(sb);
Output: Hello World 2017
Insert()
class Demo {
public static void main(String[] args) {
StringBuffer str = new StringBuffer("test");
str.insert(2, 123);
System.out.println(str);
}
} Output
te123st
reverse():
• Reverses the existing String or character sequence content in the buffer and
returns it. The object must have an existing content or else a
NullPointerException is thrown.
class StringBufferExample5{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.reverse(); olleH

System.out.println(sb);//prints olleH
}
}
StringBuffer delete() method

• The delete() method of StringBuffer class deletes the string from the
specified beginIndex to endIndex.

class StringBufferExample4{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
Hlo
}
}
StringBuffer replace() method
class StringBufferExample3{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
} HJavalo

You might also like