Use of Existing Classes in java


Most common class in JAVA is Java.Lang package and its classes. Which are Object, System, Integer, Boolean, String, StringBuffer, Float, Double, Short, Long and many more.

Package: package is a set of class and files in java which is used to keep things organised. java compiler automatically includes the java.lang package in every program you make rest is your choice.

Where do these classes comes from? Well, these are the basic requirement of any java program, these are acutally base utility classes which takes off the programming load off the programmer.

Using these classes is really easy. for example the Use of String class. Java allows you to use String class as a primitive datatype however if you want to go more OOP format you can go out with StringBuffer which is more memory efficient.

To use any of these class all you need to do is to create an object or call any method with reference of class name if in case the class is static.

for example if you are creating a string you can do it like

String s = new String("hello");
//or
Integer.parseInt("2"); //static method

There are two ways in which you can use the existing classes one is of course the java.lang package classes, which you can use directly without any extra process. Second is by importing the package or class using the import statement.

import java.util.Random;
class RandomNum{
	public static void main(String[] s){
		System.out.println(new Random().nextInt());
	}
}

This will print out any random number. The class Random is provided with java.util package which is a utility package provided with the jdk. However the import statement is required to tell the compiler to include this pacage as jdk only includes java.lang package by itslef. rest we have to take care ourself. This is so, to keep the program lightweight.

however java also provides you the privilage to create and use your own classes and packages. If you are not creating the class withing the package boundary java consider it as the defualt package.

Well to be true there is not much to tell you about using existing classes, if you know how to create an object and call method of that class using that object you know how to use the existing class.