String and Scanner

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 27

String

Course Code: CSE412 Course Title: Programming in JAVA

Dept. of Computer Science


School of Science and Engineering

Lecturer No: 5 Week No: 3 Semester: Summer 22


Lecturer: Dr. Mohammed Ashikur Rahman
Lecture Outline
1. Introduction to String
2. Implicit vs Explicit Construction
3. String Methods
4. String Equality
5. String is Immutable
6. Demonstration of String class
7. User Input using Scanner class
8. Import Packages
9. Introduction to User Defined Package
10. Create a Package
11. Hierarchy of packages
Introduction to String
Introduction

❑ Strings, which are widely used in Java programming, are a


sequence of characters.
❑ In the Java programming language, strings are objects.
❑ String objects are handled specially by the compiler.
❑ String is the only class which has implicit instantiation.
❑ The String class is defined in the java.lang package.
❑ Strings are immutable. The value of a String object can never be
changed.
Introduction to String
Creating String Objects

❑ In java objects are created using new keyword. So we can create string
objects by using the new keyword and a constructor.
String greetings = new String(“Hello”);
❑ However, String objects can be created implicitly.
String greetings = “Hello”;
❑ String can also be created using the + operator. The + operator, when
applied to Strings means concatenation.
int age = 20;
String message = “I am ” + age + “ years old”;
Implicit vs Explicit
Construction
Difference between string objects vs string literals

❑ As of we know, String can be constructed by either:


❑ One, directly assigning a string literal to a String reference - just
like a primitive.
❑ Two, via the "new" operator and constructor, like any other
classes.
❑ Difference is:
String Methods
Frequently used String Methods

❑ The String class has many methods. The most used are:
❑ length() - returns the number of characters in the String.
❑ charAt() - returns the character at the specified index.
❑ equals() - returns true if two strings have equal contents.
❑ compareTo() -returns 0 if equal, Less than zero – if the invoking String
is "less than” the other, Greater than zero - if the invoking String is
"greater than" the other.
❑ indexOf() - returns the index of specified String or character.
❑ substring() -returns a portion of the String's text.
❑ concat() – to join two strings in Java.
❑ toUpperCase(), toLowerCase() - converts the String to upper- or
lower-case characters.
String Equality
Testing Strings for Equality

❑ The == operator cannot be used to test String objects for equality.


❑ Variables of type String are references to objects (i.e.. memory
addresses)
❑ Comparing two String objects using == compares their memory
addresses. Two separate String objects may contain the equivalent text
but reside at different memory locations.
❑ Use the equals method to test for equality.
String is Immutable
String is immutable

• Since string literals with the same contents share storage in the
common pool, Java's String is designed to be immutable.
• That is, once a String is constructed, its contents cannot be
modified.
• Otherwise, the other String references sharing the same storage
location will be affected by the change, which can be
unpredictable and therefore is undesirable.
• If the contents of a String have to be modified frequently, use the
StringBuffer or StringBuilder class instead. StringBuffer and
StringBuilder is mutable.
Demonstration of String class
if(s3 == s5) {
import java.lang.*; System.out.println("yes");}
public class StringDemo {
else {
public static void main(String args[]) {
System.out.println("No");}
String s1="HELLO java";
String s2= new String(); if(s3.equals(s5)) {
String s3 = new String("Hello"); System.out.println("yes");}
String s4 = "Hello"; else {
String s5 = new String("Hello"); System.out.println("No");}
String s6 = "Hello"; String s7 = s1.substring(2,7);
String s8=new String("JaVaClaSs"); //begin index is inclusive end index is
System.out.println(s1.isEmpty()); exclusive
System.out.println(s2.isEmpty()); System.out.println(s7);
System.out.println(s1.length()); System.out.println(s1);
System.out.println(s3.charAt(1)); s1 = s1.substring(3,7);
System.out.println(s1.concat(s3)); System.out.println(s1);
System.out.println(s1); s8=s8.toLowerCase();
System.out.println(s3); System.out.println(s8);
}
Write a program for the following
output by joining two string.
Output
First String: Java
Second String: Programming
Joined String: Java Programming
Extracted String: Program
Solution
class Main
{
public static void main(String[] args)
{
// create first string
String first = "Java ";
System.out.println("First String: " + first);
// create second
String second = "Programming";
System.out.println("Second String: " + second);
// join two strings
String joinedString = first.concat(second);
System.out.println("Joined String: " + joinedString);
}
}
Scanner class

• Java provides various ways to read input from the keyboard


• The Scanner class is used to get user input
• it is found in the java.util package
• By the help of Scanner in Java, we can get input from the user in
primitive types such as int, long, double, byte, float, short, etc.
• To use the Scanner class, create an object of the class and use any of the
available methods found in the Scanner class documentation.
Scanner class methods

Method Description

nextBoolean() Reads a boolean value from the user

nextByte() Reads a byte value from the user

nextDouble() Reads a double value from the user

nextFloat() Reads a float value from the user

nextInt() Reads a int value from the user

nextLine() Reads a String value from the user

nextLong() Reads a long value from the user

nextShort() Reads a short value from the user


Scanner class demonstration
import java.util.Scanner;
class MyClass {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
System.out.println("Enter name, age and salary:");
// String input
String name = myObj.nextLine();
// Numerical input
int age = myObj.nextInt();
double salary = myObj.nextDouble();
// Output input by user
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
}
}
Introduction to User Defined Package
What is Package?

❑ Packages are a feature of the Java programming language


that help us to organize and structure our classes and their
relationships to one another.
❑ In other words, a package is a grouping of related types
providing access protection and name space management.
❑ This is the general form of the package statement:
Introduction to User Defined Package
What is Package?

❑ There are 2 types of packages:


❑ Built-in package: Already defined packages like
java.io.*, java.lang.* etc. are known as built-in
packages.
❑ User defined package: The package we create is called
user-defined package.
Introduction to User Defined Package
Why Packages are used?

❑ Preventing naming conflicts.


❑ Making searching/locating and usage of classes,
interfaces, enumerations and annotations easier.
❑ Providing controlled access.
❑ Packages can be considered as data encapsulation
(or data-hiding).
Introduction to User Defined Package
Access Protection

❑ Java’s access control mechanism may seem complicated,


we can simplify it as follows.
Private No Modifier Protected Public

Same Class Yes Yes Yes Yes

Same package subclass No Yes Yes Yes

Same package non-subclass No Yes Yes Yes

Different package subclass No No Yes Yes


Different package
No No No Yes
non-subclass
Create a Package
Package Creation Process

❑ If you do not use a package statement, your type ends up


in an unnamed package
Create a Package
Directories

❑ Java uses file system directories to store packages.


❑ For example, the .class files for any classes you declare to be part
of MyPackage must be stored in a directory called MyPackage.
❑ From last example we can say that we have to put our
HelloWorld.class file in greeting directory.
D:\greeting
HelloWorld.java
Hierarchy of packages
Example of Hierarchy of Packages

❑ We can create a hierarchy of packages.


❑ To do so, simply separate each package name from the one
above it by use of a period.
❑ The general form of a multileveled package statement is shown
here:
Naming Convention
Package Naming Convention

❑ The prefix of a unique package name is always written in


all-lowercase ASCII letters and should be one of the top-level
domain names.
❑ Subsequent components of the package name vary according to
an organization's own internal naming conventions
❑ For Example:
com.sun.eng
com.apple.quicktime.v2
edu.cmu.cs.bovik.cheese
Import Packages
How to import package

❑ Java includes the import statement to bring certain


classes, or entire packages, into visibility.
❑ Once imported, a class can be referred to directly, using
only its name.
❑ This is the general form of the import statement:
Import Packages
How to import package

❑ In a Java source file, import statements occur immediately


following the package statement (if it exists) and before any
class definitions.
❑ In the above syntax, pkg1 is the name of a top-level package,
and pkg2 is the name of a subordinate package inside the
outer package separated by a dot (.).
❑ Finally, specify either an explicit classname or a star (*), which
indicates that the Java compiler should import the entire
package
Import Packages
Example of how to import package
Books

1. Java The Complete Reference- Ninth Edition by Herbert Schildt


References

• https://docs.oracle.com/javase/tutorial/

You might also like