java lessons.docx

56
There are 8 primitive data types. he 8 primitive data types are numeric types. The names of the eight primitive data types are: byt e shor t in t lon g flo at doubl e cha r boolea n There are both integer and floating point primitive types. Integer types have no fractional part; floating point types have a fractional part. On paper, integers have no decimal point, and floating point types do. But in main memory, there are no decimal points: even floating point values are represented with bit patterns. There is a fundamental difference between the method used to represent integers and the method used to represent floating point numbers. Integer Primitive Data Types Typ e Size Range byte 8 bits -128 to +127 short 16 bits -32,768 to +32,767 int 32 bits (about)-2 billion to +2 billion long 64 bits (about)-10E18 to +10E18 Floating Point Primitive Data Types Type Size Range floa t 32 bits -3.4E+38 to +3.4E+38 doub le 64 bits -1.7E+308 to 1.7E+308 Examples int yr = 2006; double rats = 8912 ; For each primitive type, there is a corresponding wrapper class. A wrapper class can be used to convert a primitive

Transcript of java lessons.docx

There are 8 primitive data types. he 8 primitive data types are numeric types. The names of the eight primitive data types are:

byte

short

int

long

float

double

char

boolean

There are both integer and floating point primitive types. Integer types have no fractional part; floating point types have a fractional part. On paper, integers have no decimal point, and floating point types do. But in main memory, there are no decimal points: even floating point values are represented with bit patterns. There is a fundamental difference between the method used to represent integers and the method used to represent floating point numbers.

Integer Primitive Data Types

Type

Size

Range

byte

8 bits

-128 to +127

short

16 bits

-32,768 to +32,767

int

32 bits

(about)-2 billion to +2 billion

long

64 bits

(about)-10E18 to +10E18

Floating Point Primitive Data Types

Type

Size

Range

float

32 bits

-3.4E+38 to +3.4E+38

double

64 bits

-1.7E+308 to 1.7E+308

Examples

int yr = 2006;double rats = 8912 ;

For each primitive type, there is a corresponding wrapper class. A wrapper class can be used to convert a primitive data value into an object, and some type of objects into primitive data. The table shows primitive types and their wrapper classes:

primitive type

Wrapper type

byte

Byte

short

Short

int

Int

long

Long

float

Float

double

Double

char

Character

boolean

Boolean

Variables only exist within the structure in which they are defined. For example, if a variable is created within a method, it cannot be accessed outside the method. In addition, a different method can create a variable of the same name which will not conflict with the other variable. A java variable can be thought of as a little box made up of one or more bytes that can hold a value of a particular data type:

Syntax: variabletype variablename = data;

Source Code ( demonstrating declaration of a variable )

class example{ public static void main ( String[] args ) { long x = 123; //a declaration of a variable named x with a datatype of long System.out.println("The variable x has: " + x ); }}

Source Code

public class MaxDemo { public static void main(String args[]) { //integers byte largestByte = Byte.MAX_VALUE; short largestShort = Short.MAX_VALUE; int largestInteger = Integer.MAX_VALUE; long largestLong = Long.MAX_VALUE; //real numbers float largestFloat = Float.MAX_VALUE; double largestDouble = Double.MAX_VALUE; //other primitive types char aChar = 'S'; boolean aBoolean = true; //Display them all. System.out.println("largest byte value is " + largestByte + "."); System.out.println("largest short value is " + largestShort + "."); System.out.println("largest integer value is " + largestInteger + "."); System.out.println("largest long value is " + largestLong + "."); System.out.println("largest float value is " + largestFloat + "."); System.out.println("largest double value is " + largestDouble + "."); }}Sample Run

The largest byte value is 127.The largest short value is 32767.The largest integer value is 2147483647.The largest long value is 9223372036854775807.The largest float value is 3.4028235E38.The largest double value is 1.7976931348623157E308.

Previous 1 2 3 4 5 Next

Page 1 of 5

Copyright 2006-2009 Free Java Guide & Tutorials. A

The relation operators in Java are: ==, !=, , =. The meanings of these operators are:

Use

Returns true if

op1 + op2

op1 added to op2

op1 - op2

op2 subtracted from op1

op1 * op2

op1 multiplied with op2

op1 / op2

op1 divided by op2

op1 % op2

Computes the remainder of dividing op1 by op2

The following java program, ArithmeticProg , defines two integers and two double-precision floating-point numbers and uses the five arithmetic operators to perform different arithmetic operations. This program also uses + to concatenate strings. The arithmetic operations are shown in boldface.

public class ArithmeticProg {

public static void main(String[] args) {

//a few numbers

int i = 10;

int j = 20;

double x = 10.5;

double y = 20.5;

//adding numbers

System.out.println("Adding");

System.out.println(" i + j = " + (i + j));

System.out.println(" x + y = " + (x + y));

//subtracting numbers

System.out.println("Subtracting");

System.out.println(" i - j = " + (i - j));

System.out.println(" x - y = " + (x - y));

//multiplying numbers

System.out.println("Multiplying");

System.out.println(" i * j = " + (i * j));

System.out.println(" x * y = " + (x * y));

//dividing numbers

System.out.println("Dividing");

System.out.println(" i / j = " + (i / j));

System.out.println(" x / y = " + (x / y));

//computing the remainder resulting

//from dividing numbers

System.out.println("Modulus");

System.out.println(" i % j = " + (i % j));

System.out.println(" x % y = " + (x % y));

}

}

ava If-Else Statement

The if-else class of statements should have the following form:if (condition) {statements;}if (condition) {statements;} else {statements;}if (condition) {statements;} else if (condition) {statements;} else {statements;}

All programming languages have some form of an if statement that allows you to test conditions. All arrays have lengths and we can access that length by referencing the variable arrayname.length. We test the length of the args array as follows:

Source Code

// This is the Hello program in Javaclass Hello { public static void main (String args[]) { /* Now let's say hello */ System.out.print("Hello "); if (args.length > 0) { System.out.println(args[0]); } }}

Compile and run this program and toss different inputs at it. You should note that there's no longer an ArrayIndexOutOfBoundsException if you don't give it any command line arguments at all.

What we did was wrap the System.out.println(args[0]) statement in a conditional test, if (args.length > 0) { }. The code inside the braces, System.out.println(args[0]), now gets executed if and only if the length of the args array is greater than zero. In Java numerical greater than and lesser than tests are done with the > and < characters respectively. We can test for a number being less than or equal to and greater than or equal to with = respectively.

Testing for equality is a little trickier. We would expect to test if two numbers were equal by using the = sign. However we've already used the = sign to set the value of a variable. Therefore we need a new symbol to test for equality. Java borrows C's double equals sign, ==, to test for equality. Lets look at an example when there are more then 1 statement in a branch and how braces are used indefinitely.

Source Code

import java.io.*;

class NumberTest

{

public static void main (String[] args) throws IOException

{

BufferedReader stdin = new BufferedReader ( new InputStreamReader( System.in ) );

String inS;

int num;

System.out.println("Enter an integer number");

inS = stdin.readLine();

num = Integer.parseInt( inS ); // convert inS to int using wrapper classes

if ( num < 0 ) // true-branch

{

System.out.println("The number " + num + " is negative");

System.out.println("negative number are less than zero");

}

else // false-branch

{

System.out.println("The number " + num + " is positive");

System.out.print ("positive numbers are greater ");

System.out.println("or equal to zero ");

}

System.out.println("End of program"); // always executed

}

}

All conditional statements in Java require boolean values, and that's what the ==, , = operators all return. A boolean is a value that is either true or false. Unlike in C booleans are not the same as ints, and ints and booleans cannot be cast back and forth. If you need to set a boolean variable in a Java program, you have to use the constants true and false. false is not 0 and true is not non-zero as in C. Boolean values are no more integers than are strings.

Else

Lets look at some examples of if-else://Example 1if(a == b) {c++;}if(a != b) {c--;}//Example 2if(a == b) {c++;}else {c--;}We could add an else statement like so:

Source Code

// This is the Hello program in Javaclass Hello { public static void main (String args[]) { /* Now let's say hello */ System.out.print("Hello "); if (args.length > 0) { System.out.println(args[0]); } else { System.out.println("whoever you are"); } }}

Source Code

public class divisor{public static void main(String[] args) int a = 10; int b = 2; if ( a % b == 0 ) { System.out.println(a + " is divisible by "+ b); } else { System.out.println(a + " is not divisible by " + b); }}

Now that Hello at least doesn't crash with an ArrayIndexOutOfBoundsException we're still not done. java Hello works and Java Hello Rusty works, but if we type java Hello Elliotte Rusty Harold, Java still only prints Hello Elliotte. Let's fix that.

We're not just limited to two cases though. We can combine an else and an if to make an else if and use this to test a whole range of mutually exclusive possibilities.

Lets look at some examples of if-else-if://Example 1if(color == BLUE)) {System.out.println("The color is blue.");}else if(color == GREEN) {System.out.println("The color is green.");}//Example 2if(employee.isManager()) {System.out.println("Is a Manager");}else if(employee.isVicePresident()) {System.out.println("Is a Vice-President");}else {System.out.println("Is a Worker");}Source Code

// This is the Hello program in Javaclass Hello { public static void main (String args[]) { /* Now let's say hello */ System.out.print("Hello "); if (args.length == 0) { System.out.print("whoever you are"); } else if (args.length == 1) { System.out.println(args[0]); } else if (args.length == 2) { System.out.print(args[0]); System.out.print(" "); System.out.print(args[1]); } else if (args.length == 3) { System.out.print(args[0]); System.out.print(" "); System.out.print(args[1]); System.out.print(" "); System.out.print(args[2]); } System.out.println(); }}

A method is a group of instructions that is given a name and can be called up at any point in a program simply by quoting that name. Each calculation part of a program is called a method. Methods are logically the same as C's functions, Pascal's procedures and functions, and Fortran's functions and subroutines.

When I wrote System.out.println("Hello World!"); in the first program we were using the System.out.println() method. The System.out.println() method actually requires quite a lot of code, but it is all stored for us in the System libraries. Thus rather than including that code every time we need to print, we just call the System.out.println() method.You can write and call your own methods too. Methods begin with a declaration. This can include three to five parts. First is an optional access specifier which can be public, private or protected. A public method can be called from pretty much anywhere. A private method can only be used within the class where it is defined. A protected method can be used anywhere within the package in which it is defined. Methods that aren't specifically declared public or private are protected by default. access specifier. We then decide whether the method is or is not static. Static methods have only one instance per class rather than one instance per object. All objects of the same class share a single copy of a static method. By default methods are not static. We finally specify the return type.

Next is the name of the method.

Source Code

class FactorialTest { //calculates the factorial of that number.

public static void main(String args[]) {

int n;

int i;

long result;

for (i=1; i j)

System.out.println(i+" is greater than "+j);

else

System.out.println(j+" is greater than "+i);

}

}

Program 2

//Find Minimum of 2 nos. using conditional operator

class Minof2{

public static void main(String args[]){

//taking value as command line argument.

//Converting String format to Integer value

int i = Integer.parseInt(args[0]);

int j = Integer.parseInt(args[1]);

int result = (iSmall Integer not less than the number.

->Given Number.

->Largest Integer not greater than the number.

*/

class ValueFormat{

public static void main(String args[]){

double i = 34.32; //given number

System.out.println("Small Integer not greater than the number : "+Math.ceil(i));

System.out.println("Given Number : "+i);

System.out.println("Largest Integer not greater than the number : "+Math.floor(i));

}

Program 4

/*Write a program to generate 5 Random nos. between 1 to 100, and it

should not follow with decimal point.

*/

class RandomDemo{

public static void main(String args[]){

for(int i=1;i0){

result = result + temp;

temp--;

}

System.out.println("Sum of Digit for "+num+" is : "+result);

//Logic for product of digit

temp = num;

result = 1;

while(temp > 0){

result = result * temp;

temp--;

}

System.out.println("Product of Digit for "+num+" is : "+result);

}

}

Program 7

/*Write a program to Find Factorial of Given no. */

class Factorial{

public static void main(String args[]){

int num = Integer.parseInt(args[0]); //take argument as command line

int result = 1;

while(num>0){

result = result * num;

num--;

}

System.out.println("Factorial of Given no. is : "+result);

}

}

Program 8

/*Write a program to Reverse a given no. */

class Reverse{

public static void main(String args[]){

int num = Integer.parseInt(args[0]); //take argument as command line

int remainder, result=0;

while(num>0){

remainder = num%10;

result = result * 10 + remainder;

num = num/10;

}

System.out.println("Reverse number is : "+result);

}

}

Program 9

/*Write a program to find Fibonacci series of a given no.

Example :

Input - 8

Output - 1 1 2 3 5 8 13 21

*/

class Fibonacci{

public static void main(String args[]){

int num = Integer.parseInt(args[0]); //taking no. as command line argument.

System.out.println("*****Fibonacci Series*****");

int f1, f2=0, f3=1;

for(int i=1;i