Advanced Topic in Java

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 12

java.

lang package
• java.lang is a imported by default in all the
classes that we create.
• Remember String and System class
Java.lang.Object class

• parent by default of all the classes (predefined


and user-defined) in Java.
• The methods of Object class can be used by all
the objects and arrays.
• toString() and equals() are methods of Object
class
toString() method
class Demo {
public String toString() {
return “My Demo Object created”;
}
public static void main(String args[]) {
System.out.println(new Demo()); }}

Output
My Demo Object created
Java Wrapper classes
• For each primitive type, there is a corresponding
wrapper class designed.
• Are wrapper around primitive data types.
• allow for situations where primitives cannot be used
but their corresponding objects are required.
• Normally Used to convert a numeric value to a String
or vice-versa.
• Just like String, Wrapper objects are also
immutable
Wrappers classes
Wrapper classes (contd.)
• converts primitive to wrapper
– double a = 4.3;
– Double wrp = new Double(a);
• Each wrapper provides a method to return the
primitive value.
– double r = wrp.doubleValue();
Converting Primitive types to wrapper
objects
• Integer ValueOfInt = new Integer(v)
• Float ValueOfFloat = new Float(x)
• Double ValOfDouble = new Double(y)
• Long ValueOfLong = new Long(z)
Converting wrapper objects to primitives

• int v = ValueOfInt.intValue();
• float x = ValueOfFloat.floatValue();
• long y = ValueOfLong.longValue();
• double z = ValueOfDouble.doubleValue();
Converting primitives to String Object

• String xyz = Integer.toString()


• String xyz = Float.toString()
• String xyz = Double.toString()
• String xyz = Long.toString()
Converting back from String Object to
Primitives
• int v = Integer.parseInt(xyz)
• long y = Long.parseLong(xyz)
• public float parseFloat(String x)
• public double parseDouble(String x)
• public double parseByte(String x)
• public double parseShort(String x)
• May throw NumberFormatException if the value
of the String does not represent a proper
numbers
Converting Primitives represented by
String to wrapper
• Double ValueOfDouble = Double.valueOf(xyz);
• Float ValueOfFloat = Float.valueOf(xyz);
• Integer ValueOfInteger = Integer.valueOf(xyz);
• Long ValueOfLong = Long.valueOf(xyz);
• Double ValueOfDouble = Double.valueOf(xyz);
• Float ValueOfFloat = Float.valueOf(xyz);
• Integer ValueOfInteger = Integer.valueOf(xyz);
• Long ValueOfLong = Long.valueOf(xyz);
– String argument method generates a
NumberFormatException in case the value in a String does
not contain a number.

You might also like