Data Types in Java Long/Double [P-1]

Long 

Long is a signed 64-bit type and is useful for those occasions where an int type is not large enough to hold the desired value. The range of a long is quite large. This makes it useful when big, whole numbers are needed



//Compute distance light travels using long variables
public class light {
	public static void main(String args[]) {
		int lightSpeed;
		long days;
		long seconds;
		long distance;
		
		//approximate speed of light in miles per second.
		
		lightSpeed = 186000;
		
		days = 1000; //specify number of days here.
		
		seconds = days*24*60*60; //convert into seconds.
		
		distance = lightSpeed*seconds; //compute distance;
		
		System.out.print("in "+days);
		System.out.print();
		System.out.println(distance +" miles");
		
	}

}

Output
in 1000  days light will travel about 16070400000000 miles

Double

Double precision, as denoted by the double keyword, uses 64 bits to store a value. Double precision is actually faster than single precision on some modern processors that have been optimized for high-speed mathematical calculations. All transcendental math functions, such as sin( ), cos( ), and sqrt( ), return double values. When you need to maintain accuracy over many iterative calculations, or are manipulating large-valued



// compute the area of a circle using double variables.
public class Area {
	public static void main(String args[]) {
		double pi,r,a;
		r=10.8;  // radius of circle
		
		pi=3.1416;  // pi, approximately
		
		a = pi*r*r;  // compute area
		
		System.out.println("Area of circle is " + a);
	}

}

Output
Area of circle is 366.436224

Post a Comment

0 Comments