0% found this document useful (0 votes)
19 views11 pages

Core Java Unit 3

The document provides an overview of core Java concepts including packages, strings, and exception handling. It explains how to create and use packages, the characteristics of strings and string methods, and the types of exceptions in Java along with their handling techniques. Additionally, it covers the advantages of using StringBuffer and user-defined exceptions, along with methods to print exception information.

Uploaded by

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

Core Java Unit 3

The document provides an overview of core Java concepts including packages, strings, and exception handling. It explains how to create and use packages, the characteristics of strings and string methods, and the types of exceptions in Java along with their handling techniques. Additionally, it covers the advantages of using StringBuffer and user-defined exceptions, along with methods to print exception information.

Uploaded by

abhaypanchal2525
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

SILVER OAK UNIVERSITY

College Of Computer Application


Bachelor of Computer Application
Subject Name: Core Java
Subject Code: 4040233201
Semester- III

Unit : - 3 Package, String and Exception Handling


❖ Packages
❖ Creating Packages
❖ Using Packages
❖ java.lang Packages
❖ java.lang Objects class
❖ java.Wrapper classes

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 :
1) 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:

⮚ Step-by-Step Guide to Create a Package in Java


1. Choose a Package Name:
o A package name should be unique and follow the standard Java naming
conventions (e.g., com.company.project).
2. Create a Directory Structure:
o Packages are represented by directories in the file system. The directory
structure should reflect the package hierarchy.
o For example, if your package name is com.company.project, create a directory
structure com/company/project/.
3. Place Your Java Files:
o Within the directory corresponding to your package (com/company/project/),
place your Java source files (.java files).
o Every Java file in the package should start with a package statement indicating
its package name.
o Example package statement for a class in package com.company.project:
package com.company.project;
public class MyClass {
// Class code here
}
4. Compile Your Java Files:
o Compile your Java files using the javac command. Make sure you are in the root
directory of your source files (where com/ directory is located).
o Example:
javac com/company/project/MyClass.java

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:

✔ Step-by-Step Guide to Using Packages in Java


▪ Importing Packages:
o To use classes from another package, you need to import them using the import
statement at the beginning of your Java file.
o 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:
o Once imported, you can use the classes and their members (fields, methods) directly
in your Java code.
2) Example Walkthrough
Suppose you have a package com.company.project with a class MyClass, and you
want to use it in another class Main:
1. Directory Structure:
o Ensure your directory structure reflects the package hierarchy, as described
earlier.
2. MyClass.java:
o Define MyClass inside com.company.project:
Example: package com.company.project;
public class MyClass
{
public void display()
{
System.out.println("Hello from MyClass");
}
}
3. Main.java:
o Import MyClass and use it in Main:
Example: // Import MyClass from com.company.project package
import com.company.project.MyClass;

public class Main


{
public static void main(String[] args)
{
MyClass obj = new MyClass(); // Create an instance of MyClass
obj.display(); // Call display() method from MyClass }
}

4. Compile and Run:


o Compile both MyClass.java and Main.java (from the root directory containing
com/):
Example: javac com/company/project/MyClass.java
javac Main.java
Run the Main class:
java Main

Output:

o After running Main, you should see:

Example: Hello from MyClass

Notes:

∙ Package Naming: Ensure package names follow Java's naming conventions


(com.company.project).
∙ Import Statements: Always place import statements at the beginning of your Java file,
before any class definitions.
∙ Class Usage: Once imported, classes from other packages can be instantiated and their
methods invoked like any other class in your project.
String class:-

❖What are Strings in Java?


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

Example:
String name = "Geeks";

▪ Ways of Creating a 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 in Java:-


1. int length()
Returns the number of characters in the String. "Ankit".length(); // returns 5

2. Char charAt(int i)
Returns the character at ith index.
"Ankit".charAt(3); // returns ‘i’

3. String substring (int i)


Return the substring from the ith index character to end.
"Helloworld".substring(3); // returns “oworld”

4. String substring (int i, int j)


Returns the substring from i to j-1 index.
"helloworld".substring(2, 5); // returns “llo”

5. String concat( String str)


Concatenates specified string to the end of this string.
String s1 = ”hello”;
String s2 = ”world";
String output = s1.concat(s2); // returns “helloworld”
6. String toLowerCase()
Converts all the characters in the String to lower
case. String word1 = “HeLLo”;
String word3 = word1.toLowerCase(); // returns “hello"

7. String toUpperCase()\
Converts all the characters in the String to upper case.
String word1 = “HeLLo”;
String word2 = word1.toUpperCase(); // returns “HELLO”

8. String trim()
Returns the copy of the String, by removing whitespaces at both ends. It
does not affect whitespaces in the middle.
String word1 = “ Learn Share Learn “;
String word2 = word1.trim(); // returns “Learn Share Learn” 9. String
replace (char oldChar, char newChar)
Returns new string by replacing all occurrences of oldChar with newChar.
String s1 = “feeksforfeeks“;
String s2 = “feeksforfeeks”.replace(‘f’ ,’g’); // returns “geeksgorgeeks”
❖StringBuffer class in Java
▪ 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.

1. append() method:
The append() method concatenates the given argument with this string. Example:
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

2. insert() method:
The insert() method inserts the given string with this string at the given
position.
Example:
importjava.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

3. replace() method:

The replace() method replaces the given string from the specified beginIndex and
endIndex-1.

Example:

importjava.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

4. delete() method:
The delete() method of the StringBuffer class deletes the string from the specified
beginIndex to endIndex-1.

Example:

importjava.io.*; class A {
public static void main(String args[])
{

StringBuffer sb = new StringBuffer("Hello");


sb.delete(1, 3);
System.out.println(sb);
}

❖Advantages of using StringBuffer over String for String mechanism:- o


StringBuffer objects are mutable, meaning that you can change the contents of the
buffer without creating a new object.
o The initial capacity of a StringBuffer can be specified when it is created, or it can
be set later with the ensureCapacity() method.
o The append() method is used to add characters, strings, or other objects to
the end of the buffer.
o The insert() method is used to insert characters, strings, or other objects at a
specified position in the buffer.
o The delete() method is used to remove characters from the buffer.
o The reverse() method is used to reverse the order of the characters in the buffer.

Exception:-
⮚ Introduction:-

∙ 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.

What is Exception in Java?


∙ In Java, an exception is an event that disrupts the normal flow of the program. It is
an object which is thrown at runtime
⮚ Advantage of Exception Handling:-

∙ 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

⮚ Exception Handling Techniques:-


∙ There are mainly two types of exceptions: checked and unchecked. An error is
considered as the unchecked exception. However, according to Oracle, there are
three types of exceptions namely:
1. Checked Exception
2. Unchecked Exception
3. Error

1). Checked Exception:-

The classes that directly inherit the Throwable class except RuntimeException and Error are
known as checked exceptions. For example, IOException, SQLException, etc. Checked
exceptions are checked at compile-time.

2). Unchecked Exception:-

The classes that inherit the RuntimeException are known as unchecked exceptions. For example,
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc.
Unchecked exceptions are not checked at compile-time, but they are checked at runtime.

3). Error

Error is irrecoverable. Some example of errors are OutOfMemoryError, VirtualMachineError, AssertionError


etc.
⮚ User Defined Exception :-
∙ The built-in exceptions in Java are not able to describe a certain situation. In such
cases, users can also create exceptions, which are called ‘user-defined Exceptions’.

⮚ The advantages of Exception Handling in Java are as follows:


1. Provision to Complete Program Execution
2. Easy Identification of Program Code and Error-Handling Code
3. Propagation of Errors
4. Meaningful Error Reporting
5. Identifying Error Types

⮚Methods to print the Exception information:


1. PrintStackTrace()
This method prints exception information in the format of the Name of the exception:
description of the exception, stack trace.

Example:

//program to print the exception information using


printStackTrace() method

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

2. toString()
The toString() method prints exception information in the format of the
Name of the exception: description of the exception.

Example:

//program to print the exception information using toString()


method

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.toString());
}
}
}
Output:
java.lang.ArithmeticException: / by zero

3. getMessage()
The getMessage() method prints only the description of the exception. Example:

//program to print the exception information using getMessage() method


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

You might also like