package and some classes declaration of package usage of package package of java language

34
Package and Some Package and Some Classes Classes Declaration of Package Usage of Package Package of Java Language

Upload: cora-mcgee

Post on 17-Jan-2016

323 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Package and Some Classes Declaration of Package Usage of Package Package of Java Language

Package and Some ClassesPackage and Some ClassesPackage and Some ClassesPackage and Some Classes

Declaration of Package

Usage of Package

Package of Java Language

Page 2: Package and Some Classes Declaration of Package Usage of Package Package of Java Language

What is Package ?What is Package ?What is Package ?What is Package ?

Way to group a related class and interface into Way to group a related class and interface into one unit one unit

To resolve the name conflicts between class To resolve the name conflicts between class names names

Page 3: Package and Some Classes Declaration of Package Usage of Package Package of Java Language

Declaration of PackageDeclaration of PackageDeclaration of PackageDeclaration of Package

Declare at the beginning of source file Declare at the beginning of source file [Print1.java], [Print2.java]

package PackageName ; package PackageName ;

MyTestMyTest

PrintsPrints

Print1.classPrint1.class Print2.classPrint2.class

Page 4: Package and Some Classes Declaration of Package Usage of Package Package of Java Language

Usage of PackageUsage of PackageUsage of PackageUsage of Package

Use of absolute path name Use of absolute path name Declare to describe the full package name To resolve conflicts between class names

[AbsolutePath.java]

MyTest.Prints.Print1 m1; MyTest.Prints.Print2 m2;

MyTest.Prints.Print1 m1; MyTest.Prints.Print2 m2;

Page 5: Package and Some Classes Declaration of Package Usage of Package Package of Java Language

Use of import StatementUse of import StatementUse of import StatementUse of import Statement

Include all the classes in package Include all the classes in package import packageName.*;

[ImportTest.java]

import packageName.className ; import packageName.className ;

import MyTest.Prints.*; import MyTest.Prints.*;

Page 6: Package and Some Classes Declaration of Package Usage of Package Package of Java Language

java.lang Packagejava.lang Packagejava.lang Packagejava.lang Package

Basic class to enlarge the function of Java Basic class to enlarge the function of Java

Provide classes according to primitive type Provide classes according to primitive type (wrapper class)(wrapper class) Integer class, Double class,. ..

Page 7: Package and Some Classes Declaration of Package Usage of Package Package of Java Language

java.lang Classjava.lang Classjava.lang Classjava.lang Class

ObjectObject

NumberNumber

IntegerInteger

LongLong

FloatFloat

DoubleDouble

CharacterCharacter

SystemSystem

StringString

StringBufferStringBufferBooleanBoolean

Wrapper Class

Page 8: Package and Some Classes Declaration of Package Usage of Package Package of Java Language

Object ClassObject ClassObject ClassObject Class

Super class of all classes All classes are to inherit the methods of Object class Method

Object clone() : To copy the object equally boolean equals(Object obj) :

Compare the object as parameter with the object which calls this method int hashCode() : Calculate the hash code value of the object Class getClass() : To get Class object corresponding to object String toString() : Convert the object into string

[Ex 8.5] wait(), notify() : To control the status of thread

Page 9: Package and Some Classes Declaration of Package Usage of Package Package of Java Language

Wrapper ClassWrapper Class Wrapper ClassWrapper Class

Classes correspond to primitive type Classes correspond to primitive type int -> Integer, char -> Character, double -> Doubleint -> Integer, char -> Character, double -> Double

ReasonsReasons Role of home for constants and methods for each type When we need to deal with primitive type as object

Page 10: Package and Some Classes Declaration of Package Usage of Package Package of Java Language

Number ClassNumber Class Number ClassNumber Class

Abstract ClassAbstract Class Super Class of Integer, Long, Float, Double

Method abstract int intValue() : Convert into int type abstract long longValue() : Convert into long type abstract float floatValue() : Convert into float type abstract double doubleValue() : Convert into double type

Page 11: Package and Some Classes Declaration of Package Usage of Package Package of Java Language

Integer ClassInteger ClassInteger ClassInteger Class

ConstantConstant public static final int MAX_VALUE = 2147483647 public static final int MIN_VALUE = -2147483648

MethodMethod static int parseInt(String s) :

Convert a Number in String into int type static int parseInt(String s , int radix) :

Convert a number in String into int type with radix static String toBinaryString(int i) :

Convert into binary string form static String toHexString(int i) :

Convert into hexadecimal string form

Page 12: Package and Some Classes Declaration of Package Usage of Package Package of Java Language

Integer ClassInteger ClassInteger ClassInteger Class

[IntegerClass.java]

Interger.parseInt(s); Interger.toBinaryString(i); . . .

Interger.parseInt(s); Interger.toBinaryString(i); . . .

As it is staticmethod...

As it is staticmethod...

Page 13: Package and Some Classes Declaration of Package Usage of Package Package of Java Language

Double ClassDouble ClassDouble ClassDouble Class

ConstantConstant public static final double MAX_VALUE

=1.79769313486231570e+308 public static final double MIN_VALUE =

4.94065645841246544e-308 public static final double NaN = 0.0 / 0.0 public static final double NEGATIVE_INFINITY = -1.0 / 0.0 public static final double POSITIVE_INFINITY = 1.0 / 0.0

Page 14: Package and Some Classes Declaration of Package Usage of Package Package of Java Language

Double ClassDouble ClassDouble ClassDouble Class

the parameter is NaN or not. the parameter is NaN or not. static boolean isInfinite(double v) :

Check whether the parameter is infinite or not.

static Double valueOf(String s) : Method static long doubleToLongBits(double value) :

Convert the bits represented by double type into long type bit pattern

static boolean isNaN(double v) : Check whether Convert String into Double type

Page 15: Package and Some Classes Declaration of Package Usage of Package Package of Java Language

Boolean ClassBoolean ClassBoolean ClassBoolean Class

ConstantConstant public static final Boolean TRUE = new Boolean(true) public static final Boolean FALSE = new Boolean(false)

MethodMethod Boolean(boolean b) :

Constructor to create boolean object receiving the initial value b Boolean(String s) :

Constructor to receive the string value "true“ or "false“ boolean booleanValue() :

Return the boolean value of object static boolean getBoolean(String name) :

Return the boolean value of system attribute static Boolean valueOf(String s) :

Return the Boolean value correspond to string s

Page 16: Package and Some Classes Declaration of Package Usage of Package Package of Java Language

Character ClassCharacter ClassCharacter ClassCharacter Class

ConstantConstant public static final int MAX_RADIX = 36 public static final char MAX_VALUE =‘\ffff’ public static final int MIN_RADIX = 2 public static final char MIN_VALUE =’\0000’

MethodMethod Character(char value) : Constructor to initialize the object as value char charValue() : Convert into char type static boolean isDigit(char ch) : Test whether is digit? static boolean isLetter(char ch) : Test whether is letter? static boolean isLetterOrDigit(char ch) : Return when it is letter or

digit.

[CharacterClass.java]

Page 17: Package and Some Classes Declaration of Package Usage of Package Package of Java Language

String ClassString ClassString ClassString Class

MethodMethod char charAt(int index) :

Return the character at specific position in string

int length() : Return the length of string

String toUpperCase() : Convert the string into upper character

String toLowerCase() : Convert the string into lower character

String trim() : Remove the white space before/after string

String substring(int beginIndex) : Make the sub string from beginIndex to the end of the string

Page 18: Package and Some Classes Declaration of Package Usage of Package Package of Java Language

StringBuffer ClassStringBuffer ClassStringBuffer ClassStringBuffer Class

Provide the string sequence operation Provide the string sequence operation MethodMethod

StringBuffer append(Type obj) : Append the obj(to be changed into string) to string

StringBuffer insert(int offset, Type obj) : Insert obj(to be changed into string) into specified position

Object String char[] boolean char int long float double

Object String char[] boolean char int long float double

Page 19: Package and Some Classes Declaration of Package Usage of Package Package of Java Language

StringBuffer ClassStringBuffer ClassStringBuffer ClassStringBuffer Class

String now = new java.util.Date().toString();

StringBuffer strbuf = new StringBuffer(now);

strbuf.append(" : ").append(now.length).append('.');

System.out.println(strbuf.toString());

String now = new java.util.Date().toString();

StringBuffer strbuf = new StringBuffer(now);

strbuf.append(" : ").append(now.length).append('.');

System.out.println(strbuf.toString());

Page 20: Package and Some Classes Declaration of Package Usage of Package Package of Java Language

System ClassSystem ClassSystem ClassSystem Class

Class for Java Virtual Machine and the control and security for OS system

Define the standard input and output

Field public static InputStream in :

Stream to read data from standard input device

public static PrintStream out : Stream to output data to standard output device

public static PrintStream err : Standard Error Stream to output error message

Page 21: Package and Some Classes Declaration of Package Usage of Package Package of Java Language

Java.util.vectorJava.util.vectorJava.util.vectorJava.util.vector

 We will be creating an object of Vector class and performs various operation like adding, removing etc.

Vector class extendsAbstractList and implements List, RandomAccess, Cloneable, Serializable.

The size of a vector increase and decrease according to the program.

Vector is synchronized.

Page 22: Package and Some Classes Declaration of Package Usage of Package Package of Java Language

Methods in VectorMethods in VectorMethods in VectorMethods in Vector

add(Object o): It adds the element in the end of the Vector

size(): It gives the number of element in the vector. elementAt(int index): It returns the element at the

specified index. firstElement(): It returns the first element of the

vector. lastElement(): It returns  last element. removeElementAt(int index): It deletes the

element from the given index.

Page 23: Package and Some Classes Declaration of Package Usage of Package Package of Java Language

Methods in Vector classMethods in Vector classMethods in Vector classMethods in Vector class

elements(): It returns an enumeration of the element

In this example we have also used Enumeration interface to retrieve the value of a vector. Enumerationinterface has two methods.

hasMoreElements(): It checks if this enumeration contains more elements or not.

nextElement(): It checks the next element of the enumeration.

Page 24: Package and Some Classes Declaration of Package Usage of Package Package of Java Language

import java.util.*;public class VectorDemo{  public static void main(String[] args){    Vector<Object> vector = new Vector<Object>();    int primitiveType = 10;    Integer wrapperType = new Integer(20);    String str = "tapan joshi";    vector.add(primitiveType);    vector.add(wrapperType);    vector.add(str);    vector.add(2, new Integer(30));

Page 25: Package and Some Classes Declaration of Package Usage of Package Package of Java Language

System.out.println("the elements of vector: " + vector);System.out.println("The size of vector are: " + vector.size());System.out.println("The elements at position 2 is: " + vector.elementAt(2));System.out.println("The first element of vector is: " + vector.firstElement());System.out.println("The last element of vector is: " + vector.lastElement());vector.removeElementAt(2);Enumeration e=vector.elements();System.out.println("The elements of vector: " + vector);while(e.hasMoreElements()){System.out.println("The elements are: " + e.nextElement());}  }}

Page 26: Package and Some Classes Declaration of Package Usage of Package Package of Java Language

Example on Stack classExample on Stack classExample on Stack classExample on Stack class

import java.util.*;

public class StackDemo{  public static void main(String[] args) {    Stack stack=new Stack();    stack.push(new Integer(10));    stack.push("a");    System.out.println("The contents of Stack is" + stack);    System.out.println("The size of an Stack is" + stack.size());    System.out.println("The number poped out is" + stack.pop());    System.out.println("The number poped out is " + stack.pop());    //System.out.println("The number poped out is" + stack.pop());    System.out.println("The contents of stack is" + stack);    System.out.println("The size of an stack is" + stack.size());  }}

Page 27: Package and Some Classes Declaration of Package Usage of Package Package of Java Language

Example on Scanner Example on Scanner classclassExample on Scanner Example on Scanner classclass

import java.util.Scanner;import java.util.Scanner;

public class ScannerDemo {public class ScannerDemo {

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

Scanner scanner = new Scanner(System.in);Scanner scanner = new Scanner(System.in);

// Read string input for username// Read string input for username

System.out.print("Username: ");System.out.print("Username: ");

String username = scanner.nextLine();String username = scanner.nextLine();

// Read string input for password// Read string input for password

System.out.print("Password: ");System.out.print("Password: ");

String password = scanner.nextLine();String password = scanner.nextLine();

Page 28: Package and Some Classes Declaration of Package Usage of Package Package of Java Language

// Read an integer input for another challenge// Read an integer input for another challenge

System.out.print("What is 2 + 2: ");System.out.print("What is 2 + 2: ");

int result = scanner.nextInt();int result = scanner.nextInt();

if (username.equals("admin") && password.equals("secret") && if (username.equals("admin") && password.equals("secret") && result == 4) {result == 4) {

System.out.println("Welcome to Java Application");System.out.println("Welcome to Java Application");

} else {} else {

System.out.println("Invalid username or password, access System.out.println("Invalid username or password, access denied!");denied!");

}}

}}

}}

Page 29: Package and Some Classes Declaration of Package Usage of Package Package of Java Language

Example on Date ClassExample on Date ClassExample on Date ClassExample on Date Class

import java.util.*;

public class  DateDemo{  public static void main(String[] args) {    Date d=new Date();    System.out.println("Today date is "+ d);  }}

Page 30: Package and Some Classes Declaration of Package Usage of Package Package of Java Language

JAVA.IOJAVA.IO

Page 31: Package and Some Classes Declaration of Package Usage of Package Package of Java Language

Example on FileExample on FileExample on FileExample on File

import java.io.*;class FileWrite {   public static void main(String args[])  {      try{    // Create file     FileWriter fstream = new FileWriter("out.txt",true);        BufferedWriter out = new BufferedWriter(fstream);    out.write("Hello Java");    //Close the output stream    out.close();    }catch (Exception e){//Catch exception if any      System.err.println("Error: " + e.getMessage());    }  }}

Page 32: Package and Some Classes Declaration of Package Usage of Package Package of Java Language

java.io.Reader classjava.io.Reader class

Page 33: Package and Some Classes Declaration of Package Usage of Package Package of Java Language

BufferedReader classBufferedReader class

 Method Return Type

 Description

 read( )  int  Reads a single character 

 read(char[] cbuf, int off, int len)

 int Read characters into a portion of an array.

 readLine( )  String Read a line of text. A line is considered to be  terminated by ('\n').

  close( )  void   Closes the opened stream.

Page 34: Package and Some Classes Declaration of Package Usage of Package Package of Java Language

import java.io.*;  public class ReadStandardIO{    public static void main(String[] args) throws IOException{

      InputStreamReader inp = new InputStreamReader(System.in)       BufferedReader br = new BufferedReader(inp);

      System.out.println("Enter text : ");       String str = in.readLine();

     System.out.println("You entered String : ");

      System.out.println(str);  }}