Java-03-Package, String, Exception
Java-03-Package, String, Exception
JAVA-03
SOUNotes.com
SOUNotes.com
Java-03-Package, String, Exception
Packages
Package in Java is a mechanism to encapsulate a group of classes, sub packages and
interfaces.
Packages are used for:
Preventing naming conflicts. For example there can be two classes with name
Employee in two packages, college.staff.cse.Employee and
college.staff.ee.Employee
Making searching/locating and usage of classes, interfaces, enumerations and
annotations easier
Providing controlled access: protected and default have package level access control. A
protected member is accessible by classes in the same package and its subclasses. A
default member (without any access specifier) is accessible by classes in the same
package only.
Packages can be considered as data encapsulation (or data-hiding).
Creating Package
Creating a package in Java is a way to organize your classes and interfaces into
namespaces, making it easier to manage and locate them within your project. Here’s a
step-by-step guide to creating a package:
package com.company.project;
public class MyClass {
// Class code here
}
Using Packages
Using packages in Java involves importing classes from other packages into your Java source
files so that you can utilize their functionality. Here’s a step-by-step guide on how to use
packages in Java:
Importing Packages:
To use classes from another package, you need to import them using the import
statement at the beginning of your Java file.
There are different ways to import classes:
Import a single class. Example: import packageName.ClassName;
Import all classes in a package (not recommended due to potential naming
conflicts). Example: import packageName.*;
Import a static member.
Example: import static packageName.ClassName.staticMember;
Using Classes from Imported Packages:
Once imported, you can use the classes and their members (fields, methods) directly in
your Java code
Example
Suppose you have a package com.company.project with a class MyClass , and you want to use
it in another class Main:
Directory Structure: Ensure your directory structure reflects the package hierarchy, as
described earlier
MyClass.java : Define MyClass inside com.company.project
package com.company.project;
Compile and Run: Compile both MyClass.java and Main.java (from the root directory
containing com/ )
javac com/company/project/MyClass.java
javac Main.java
java Main
Output:
Important
String Class
Strings are the type of objects that can store the character of values and in Java, every
character is stored in 16 bits i.e. using UTF 16-bit encoding.
A string acts the same as an array of characters in Java
Ways of creating String:
There are two ways to create a string in Java:
String Literal
Example: String demoString = “Ankit”;
Using New Keyword:
Example: String demoString = new String (“GeeksforGeeks”);
String Methods
int length()
Returns the number of characters in the String.
"Ankit".length(); // returns 5
Char charAt(int i)
Returns the character at ith index.
"Ankit".charAt(3); // returns ‘i’
String substring(int i)
Return the substring from the ith index character to end.
"Helloworld".substring(3); // returns “oworld”
String s1 = ”hello”;
String s2 = ”world";
String output = s1.concat(s2); // returns “helloworld”
String toLowerCase()
Converts all the characters in the String to lower
String toUpperCase()
Converts all the characters in the String to upper case.
String trim()
Returns the copy of the String, by removing whitespaces at both ends. It does not
affect whitespaces in the middle.
String s1 = “feeksforfeeks“;
String s2 = “feeksforfeeks”.replace(‘f’ ,’g’); // returns “geeksgorgeeks”
StringBuffer Class
StringBuffer is a class in Java that represents a mutable sequence of characters.
It provides an alternative to the immutable String class, allowing you to modify the
contents of a string without creating a new object every time
append() Method:
The append() method concatenates the given argument with this string.
import java.io.*;
class A {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("Hello ");
sb.append("Java"); // now original string is changed
System.out.println(sb);
}
}
// OUTPUT
// Hello Java
insert() Method:
The insert() method inserts the given string with this string at the given position.
import java.io.*;
class A {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("Hello ");
sb.insert(1, "Java"); // Now original string is changed
System.out.println(sb);
}
}
// OUTPUT
// HJavaello
replace() Method:
The replace() method replaces the given string from the specified beginIndex and
endIndex-1 .
import java.io.*;
class A {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("Hello");
sb.replace(1, 3, "Java");
System.out.println(sb);
}
}
// OUTPUT
// HJavalo
delete() Method:
The delete() method of the StringBuffer class deletes the string from the specified
beginIndex to endIndex-1 .
import java.io.*;
class A {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("Hello");
sb.delete(1, 3);
System.out.println(sb);
}
}
// OUTPUT
// Hlo
Exception
An exception is an event, which occurs during the execution of a program, that disrupts the
normal flow of the program's instructions. When an error occurs within a method, the
method creates an object and hands it off to the runtime system
In Java, an exception is an event that disrupts the normal flow of the program. It is an
object which is thrown at runtime
The core advantage of exception handling is to maintain the normal flow of the
application. An exception normally disrupts the normal flow of the application
import java.io.*;
class GFG {
public static void main (String[] args) {
int a=5;
int b=0;
try {
System.out.println(a/b);
}
catch (ArithmeticException e) {
e.printStackTrace();
}
}
}
// OUTPUT
// java.lang.ArithmeticException: / by zero
// at GFG.main(GFG.java:10)
toString() : The toString() method prints exception information in the format of the
Name of the exception: description of the exception.
class GFG1 {
public static void main (String[] args) {
int a=5;
int b=0;
try {
System.out.println(a/b);
}
catch(ArithmeticException e) {
System.out.println(e.toString());
}
}
}
// OUTPUT
// java.lang.ArithmeticException: / by zero
getMessage() : The getMessage() method prints only the description of the exception.
import java.io.*;
class GFG1 {
public static void main (String[] args) {
int a=5;
int b=0;
try {
System.out.println(a/b);
}
catch(ArithmeticException e) {
System.out.println(e.getMessage());
}
}
}
// OUTPUT
// / by zero
Questions
1. What is a package in java programming, and how do you create one? Explain steps of it.
2. What is String class? Explain its method in java.
3. What is StringBuffer class in java? Give advantage of it and explain with its method.
4. Write down difference between String and StringBuffer.
5. What is Exception in java?
6. What are the Exception Handling Technique? Explain in detail.
7. What are the Methods to print the Exception information? Explain in detail
Telegram: @soubca Site: SOUNotes
17 of 17