0% found this document useful (0 votes)
4 views

Ch.10UsingLibrayClasses-1

Chapter 10 covers the use of library classes and packages in Java, detailing built-in and user-defined packages, their advantages, and how to import them. It explains variable initialization methods, including static and dynamic initialization, and demonstrates input handling using the Scanner class. Additionally, the chapter discusses wrapper classes, autoboxing, unboxing, and string manipulation using various classes such as String, StringBuffer, and StringTokenizer.

Uploaded by

btbtr24122shalvi
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)
4 views

Ch.10UsingLibrayClasses-1

Chapter 10 covers the use of library classes and packages in Java, detailing built-in and user-defined packages, their advantages, and how to import them. It explains variable initialization methods, including static and dynamic initialization, and demonstrates input handling using the Scanner class. Additionally, the chapter discusses wrapper classes, autoboxing, unboxing, and string manipulation using various classes such as String, StringBuffer, and StringTokenizer.

Uploaded by

btbtr24122shalvi
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/ 9

Ch.

10: Using Library Classes and Packages

10.1 Packages : A package is a named collection of logically related classes. There are two
types of packages in Java.
1. Built-in package
2. User defined package
Common built-in packages in Java:

Package Description
java.lang (Default package) Provides classes for primitive data types, String and Math
functions.
java.io Provides classes for input and output of data

java.util Provide classes for printing, scanning etc.

java.applet Provides classes to implement applets.

java.awt Provides classes to implement GUI

java.net Provides classes for networking

10.1.1 Importing Packages : The general syntax to import a built-in package in java is
import java.package.[subpackage].class; []  optional

e.g. import java.util.Scanner;


Above statement will take reference of the class Scanner defined in java.util package.
We can call all the classes of a package using the wild card character asterisk (*) as:
import java.util.*;
Above statement will take reference of all classes defined in java.util package.
10.1.2 Advantages of using Packages :
1. Packages group related classes so that they can be managed effectively.
2. The Classes contained in other packages can easily be reused.
10.2 Initialization : The processes of assigning a value to the variable is called initialization. A
variable can be initialized in two ways:
Static initialization: Initializing a variable before the execution of a program is called static
initialization.
e.g. Input using assignment operator.
Dynamic initialization: Initializing a variable during the execution of a program is called
dynamic initialization.
e.g. 1. Input using parameters (BlueJ).
2. Input using Scanner class.
10.2.1 Input using Assignment : In this method, a variable is initialized with the help of
assignment operator( = ) before the execution of the program.
e.g. Write a program to calculate the simple interest and Total amount with the given
values:
P= Rs. 20000 , R =8.9% and T=3 years
public class Interest
{
public static void main (String args[])
{
int P=20000,T=3; // Input using assignment
double R= 8.9; // Input using assignment
double SI,TA;
SI= P*R*T/100;
TA = P + SI;
System.out.println (“Simple interest = “ + SI);
System.out.println (“Total amount = “ + TA);
} OUTPUT
}
10.2.2 Input using parameter(using BlueJ system) : In this system, the variables for the
values to be input are declared as parameters of the main () function. The data values
are passed to the main () at the time of execution.
e.g. Write a program to find the area of a rectangle if its dimensions are given.
public class Rectangle
{ // Input using parameters
public static void main(int len,int width)
{
double area=len*width ;
System.out.println ("Area of the Rectangle = " + area);
}
}
Output

10.2.3 Input using the Scanner Class : To input a value using the Scanner class, we will
follow given steps:
Step 1: Scanner class is defined in java.util package hence import package java.util as:
import java.util.Scanner;
or
import java.util.*;
Step 2: Create an object for the Scanner class to access its functions as: To accept input
from keyboard
Scanner sc = new Scanner (System.in);

<class name> <object> = new <class name> (argument);


Step 3: Using any of the following methods accept value from the keyboard.
Method Description
next() To accept a String.
nextLine() To accept a sentence.
nextInt() To accept an integer value.
nextShort () To accept a short integer value.
nextLong () To accept a long integer value.
nextFloat () To accept a floating (i.e. real) value.
nextDouble () To accept a double (i.e. real) value with more precisions.
next().charAt(0) To accept a single character.

e.g. : Write a program that accept the temperature in Fahrenheit and converts and display
its equivalent temperature in Celsius.
import java.util.*; //Step 1
public class temperature
{
public static void main(String args[])
{
double f,c;
Scanner sc = new Scanner(System.in); //Step 2
System.out.println("Enter the temperature in Fahrenheit");
f=sc.nextDouble(); //Step 3
c=5*(f-32)/9;
System.out.println(f + " degree Fahrenheit = "+c+" degree Celsius");
}
}
Output

10.3 Wrapper Class


The wrapper class in Java provides the mechanism to convert primitive into object and object
into primitive.

Use of Wrapper classes in Java

o Change the value in Method: Java supports only call by value. So, if we pass a primitive
value, it will not change the original value. But, if we convert the primitive value in an
object, it will change the original value.
o java.util package: The java.util package provides the utility classes to deal with objects.

The eight classes of the java.lang package are known as wrapper classes in Java. The list of
eight wrapper classes are given below:

Primitive Type Wrapper class

boolean Boolean

char Character

byte Byte

short Short

int Integer

long Long

float Float

double Double
Autoboxing

The automatic conversion of primitive data type into its corresponding wrapper class is known
as autoboxing, for example, byte to Byte, char to Character, int to Integer etc. we do not need
to use the valueOf() method of wrapper classes to convert the primitive into objects.

//Autoboxing example of int to Integer

public class WrapperExample1


{
public static void main(String args[])
{

int a=20;
Integer i=Integer.valueOf(a); //converting int into Integer explicitly
Integer j=a; //autoboxing
System.out.println(a+" "+i+" "+j);
}
}

Output:

20 20 20

Unboxing

The automatic conversion of wrapper type into its corresponding primitive type is known as
unboxing. It is the reverse process of autoboxing.

//Unboxing example of Integer to int

public class WrapperExample2


{
public static void main(String args[])
{
Integer a=new Integer(3);
int i=a.intValue(); //converting Integer to int explicitly
int j=a; //unboxing
System.out.println(a+" "+i+" "+j);
} }

Output: 333
10.3 Working with Strings: A String can be defined as a group of characters.

To deal with single character data, we have the Character class, which is a wrapper class.
Character class: This class offers many methods to manipulate or inspect single-character
data.
e.g.
Character.isUpperCase(char ch); // returns true if the character ‘ch’ is in upper case.

To deal with group of characters, we have following classes in Java:

1. String class: The Java String class provides a lot of methods to perform operations on
strings such as compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(),
substring() etc.

In java, String objects are immutable. Immutable simply means unmodifiable or


unchangeable. Once string object is created its data or state can't be changed but a new string
object is created.
2. StringBuffer class: The Java StringBuffer class is used to create mutable (modifiable)
string. The StringBuffer class in java is same as String class except it is mutable i.e. it can be
changed.
3. StringBuilder class: Java StringBuilder class is used to create mutable (modifiable) string.
The Java StringBuilder class is same as StringBuffer class except that it is non-synchronized.

4. StringTokenizer class: The java.util.StringTokenizer class allows you to break a string


into tokens (words separated by a delimeter).

10.4 Instantiation (Creating and initializing an object of string)

(i) String class

Implicit Instantiation
String <object>=”value”;
e.g. String str=”Java Programming”;
Explicit Instantiation
String <object> = new String (“Value”);
e.g. String str=new String(“Java Programming”);
(ii) StringBuffer class
StringBuffer <object> = new StringBuffer(“value”);
e.g. StringBuffer str= new StringBuffer(“Java Programming”);

(iii) StringTokenizer class


StringTokenizer <object> = new StringTokenizer (String object, delimiter(s));
e.g. String str=”Java Programming.”;
StringTokenizer st = new StringTokenizer (str,” ?,!.”);
Note. We give delimiters (characters which separate words) without any separators.

E.G

import java.util.*;
class SortWords
{
public static void main()
{
Scanner sc = new Scanner(System.in);
String str,str1="",w;
int l,i;
System.out.println("Enter the Sentence");
str=sc.nextLine();
int len=str.length();
char lch=str.charAt(len-1); // To store last character
if(lch=='.' || lch=='?' || lch=='!' )
{
str=str.toUpperCase(); //To convert string in UpperCase
StringTokenizer st=new StringTokenizer(str," ,?!.");
l=st.countTokens(); //To count no. of words
System.out.println("No. of words in Sentence = "+l);
for(i=0;i<l;i++)
{
w=st.nextToken(); //To get word from the sentence
String ws="";
// To arrange characters of word in alphabetical order
for(char ch='A';ch<='Z';ch++)
{
for(int j=0;j<w.length();j++)
{
if(w.charAt(j)==ch)
ws=ws+w.charAt(j);
}
}
str1= str1 +ws+" ";
}
System.out.println("Original Sentence :"+str);
System.out.println("Resultant Sentence :"+str1);
} // end of if
else // if sentence is not terminated with ‘.’ , ’?’ or ‘!’
System.out.println("INVALID INPUT");
}
}

You might also like