Skip to main content

By clicking Submit, you agree to the developerWorks terms of use.

The first time you sign into developerWorks, a profile is created for you. Select information in your developerWorks profile is displayed to the public, but you may edit the information at any time. Your first name, last name (unless you choose to hide them), and display name will accompany the content that you post.

All information submitted is secure.

  • Close [x]

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerworks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

By clicking Submit, you agree to the developerWorks terms of use.

All information submitted is secure.

  • Close [x]

Java certification success, Part 1: SCJP

Pradeep Chopra, Cofounder, WHIZlabs Software

Summary:  This tutorial is designed to prepare programmers for the Sun Certified Java Programmer (SCJP) 1.4 exam, providing a detailed overview of all the exam's main objectives.

Date:  06 Nov 2003
Level:  Introductory PDF:  A4 and Letter (162 KB | 50 pages)Get Adobe® Reader®

Activity:  18093 views
Comments:  

Fundamental classes in the java.lang package

Using the Math class

The Math class is final and all the methods defined in the Math class are static, which means you cannot inherit from the Math class and override these methods. Also, the Math class has a private constructor, so you cannot instantiate it.

The Math class has the following methods: ceil(), floor(), max(), min(), random(), abs(), round(), sin(), cos(), tan(), and sqrt().

The ceil() method returns the smallest double value that is not less than the argument and is equal to a mathematical integer. For instance:

  Math.ceil(5.4)          // gives 6
  Math.ceil(-6.3)         // gives -6

The floor() method returns the largest double value that is not greater than the argument and is equal to a mathematical integer. For instance:

  Math.floor(5.4)         // gives 5
  Math.floor(-6.3)        // gives -7

The max() method takes two numeric arguments and returns the greater of the two. It is overloaded for int, long, float, or double arguments. For instance:

  x = Math.max(10,-10);	// returns 10	

The min method takes two numeric arguments and returns the smaller of the two. It is overloaded for int, long, float, or double arguments. For instance:

  x = Math.min(10,-10);	// returns -10	

The random() method returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.

The abs() method returns the absolute value of the argument. It is overloaded to take an int, long, float, or double argument. For instance:

  Math.abs(-33)		// returns 33

The round() method returns the integer closest to the argument (overloaded for float and double arguments). If the number after the decimal point is less than 0.5, Math.round() returns the same result as Math.floor(). In all the other cases, Math.round() works the same as Math.ceil(). For instance:

  Math.round(-1.5)  // result is -1
  Math.round(1.8)   // result is 2  	

Trigonometric functions
The sin(), cos(), and tan() methods return the sine, cosine, and tangent of an angle, respectively. In all three methods, the argument is the angle in radians. Degrees can be converted to radians by using Math.toRadians(). For instance:

  x = Math.sin(Math.toRadians(90.0));	// returns 1.0

The sqrt() function returns the square root of an argument of type double. For instance:

  x = Math.sqrt(25.0);	// returns 5.0

If you pass a negative number to the sqrt() function, it returns NaN ("Not a Number").


String and StringBuffer

Immutability of String objects
As you know, String s are objects in Java code. These objects, however, are immutable. That is, their value, once assigned, can never be changed. For instance:

  String msg = "Hello";
  msg += " World";	 

Here the original String "Hello" is not changed. Instead, a new String is created with the value "Hello World" and assigned to the variable msg. It is important to note that though the String object is immutable, the reference variable is not.

String literals
In Java code, the String literals are kept in a memory pool for efficient use.

If you construct two String s using the same String literal without the new keyword, then only one String object is created. For instance:

  String s1 = "hello";
  String s2 = "hello"; 

Here, both s1 and s2 point to the same String object in memory. As we said above, String objects are immutable. So if we attempt to modify s1, a new modified String is created. The original String referred to by s2, however, remains unchanged.

StringBuffer
StringBuffer objects are mutable, which means their contents can be changed. For instance:

  Stringbuffer s = new StringBuffer("123");
  s.append("456");	// Now s contains "123456"

You can see how this differs from the String object:

  String s = new String("123");
  s.concat("456");	// Here s contains "123"


Wrapper classes

Wrapper classes correspond to the primitive data types in the Java language. These classes represent the primitive values as objects. All the wrapper classes except Character have two constructors -- one that takes the primitive value and another that takes the String representation of the value. For instance:

  Integer i1 = new Integer(50);
  Integer i2 = new Integer("50");

The Character class constructor takes a char type element as an argument:

  Character c = new Character('A');

Wrapper objects are immutable. This means that once a wrapper object has a value assigned to it, that value cannot be changed.

The valueOf() method
All wrapper classes (except Character ) define a static method called valueOf(), which returns the wrapper object corresponding to the primitive value represented by the String argument. For instance:

  Float f1 = Float.valueOf("1.5f");

The overloaded form of this method takes the representation base (binary, octal, or hexadecimal) of the first argument as the second argument. For instance:

  Integer I = Integer.valueOf("10011110",2);

Converting wrapper objects to primitives
All the numeric wrapper classes have six methods, which can be used to convert a numeric wrapper to any primitive numeric type. These methods are byteValue, doubleValue, floatValue, intValue, longValue, and shortValue. An example is shown below:

  Integer i = new Integer(20);
  byte b = i.byteValue();

Parser methods
The six parser methods are parseInt, parseDouble, parseFloat, parseLong, parseByte, and parseShort. They take a String as the argument and convert it to the corresponding primitive. They throw a NumberFormatException if the String is not properly formed. For instance:

  double d = Double.parseDouble("4.23");

It can also take a radix(base) as the second argument:

  int i = Integer.parseInt("10011110",2);

Base conversion
The Integer and Long wrapper classes have methods like toBinaryString() and toOctalString(), which convert numbers in base 10 to other bases. For instance:

  String s = Integer.toHexString(25);


Summary

We discussed the usage and signature of the various utility methods of the Math class. You are expected to memorize these for the exam. We also saw how String objects are immutable, while StringBuffer objects are not. The wrapper classes provide utility methods that allow you to represent primitives as objects. Make sure you are familiar with all the parsing and conversion methods.


Exercise

Question:

What will be the result of an attempt to compile and run the following program?

  class Test 
  {
    public static void main(String args[])	
    {
      String s1 = "abc";
      String s2 = "abc";
      s1 += "xyz";
      s2.concat("pqr");
      s1.toUpperCase();
      System.out.println(s1 + s2);
    }
  }

Choices:

  • A. "abcxyzabc"
  • B. "abcxyzabcpqr"
  • C. "ABCXYZabcpqr"
  • D. "ABCXYZabc"
  • E. Code does not compile

Correct choice:

  • A

Explanation:

This code compiles and runs without errors, printing "abcxyzabc." In the given code, s1 and s2 initially refer to the same String object "abc." When "xyz" is concatenated to s1, a new String object "abcxyz" is created and s1 is made to refer to it. Note that s2 still refers to the original String object "abc," which is unchanged. The concat() and toUpperCase() methods do not have any effect, because the new String objects created as a result of these operations do not have any references stored. So s1 contains "abcxyz" and s2 contains "abc" at the end, making A the correct result.

9 of 13 | Previous | Next

Comments



Help: Update or add to My dW interests

What's this?

This little timesaver lets you update your My developerWorks profile with just one click! The general subject of this content (AIX and UNIX, Information Management, Lotus, Rational, Tivoli, WebSphere, Java, Linux, Open source, SOA and Web services, Web development, or XML) will be added to the interests section of your profile, if it's not there already. You only need to be logged in to My developerWorks.

And what's the point of adding your interests to your profile? That's how you find other users with the same interests as yours, and see what they're reading and contributing to the community. Your interests also help us recommend relevant developerWorks content to you.

View your My developerWorks profile

Return from help

Help: Remove from My dW interests

What's this?

Removing this interest does not alter your profile, but rather removes this piece of content from a list of all content for which you've indicated interest. In a future enhancement to My developerWorks, you'll be able to see a record of that content.

View your My developerWorks profile

Return from help

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Java technology
ArticleID=132290
TutorialTitle=Java certification success, Part 1: SCJP
publish-date=11062003
author1-email=
author1-email-cc=

Tags

Help
Use the search field to find all types of content in My developerWorks with that tag.

Use the slider bar to see more or fewer tags.

Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere).

My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).

Use the search field to find all types of content in My developerWorks with that tag. Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere). My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).