my java notes

Upload: guru-da

Post on 07-Apr-2018

249 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/4/2019 My Java Notes

    1/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    Relational operator

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

    UseReturns

    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. Thisprogram also uses + to concatenate strings. The arithmetic operations are shown in boldface.

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

    //a few numbersint i = 10;int j = 20;double x = 10.5;double y = 20.5;

    //adding numbersSystem.out.println("Adding");System.out.println(" i + j = " + (i + j));System.out.println(" x + y = " + (x + y));

    //subtracting numbersSystem.out.println("Subtracting");System.out.println(" i - j = " + (i - j));

  • 8/4/2019 My Java Notes

    2/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

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

    //multiplying numbersSystem.out.println("Multiplying");System.out.println(" i * j = " + (i * j));System.out.println(" x * y = " + (x * y));

    //dividing numbersSystem.out.println("Dividing");System.out.println(" i / j = " + (i / j));System.out.println(" x / y = " + (x / y));

    //computing the remainder resulting//from dividing numbersSystem.out.println("Modulus");System.out.println(" i % j = " + (i % j));System.out.println(" x % y = " + (x % y));

    }}Java Increment and Decrement Operators

    There are 2 Increment or decrement operators -> ++ and --. These two operators are unique in thatthey can be written both before the operand they are applied to, called prefix increment/decrement, orafter, called postfix increment/decrement. The meaning is different in each case.

    Examplex = 1;y = ++x;System.out.println(y);

    prints 2, but

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

    prints 1Source Code

    //Count to ten

    class UptoTen {

    public static void main (String args[]) {int i;

    for (i=1; i

  • 8/4/2019 My Java Notes

    3/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    }

    }When we write i++ we're using shorthand for i = i + 1. When we say i-- we're using shorthand for i = i -1. Adding and subtracting one from a number are such common operations that these specialincrement and decrement operators have been added to the language. T There's another short hand for the general add and assign operation, +=. We would normally write

    this as i += 15. Thus if we wanted to count from 0 to 20 by two's we'd write: Source Code

    class CountToTwenty {

    public static void main (String args[]) {int i;for (i=0; i = 0; i -= 2) { //Note Decrement Operator by 2System.out.println(i);

    }}

    }

    relational operatorA relational operator compares two values and determines the relationship between them. Forexample, != returns true if its two operands are unequal. Relational operators are used to test whethertwo values are equal, whether one value is greater than another, and so forth. The relation operatorsin Java are: ==, !=, , =. The meanings of these operators are:

    UseReturns

    true if

    op1 > op2

    op1 is

    greater

    than

    op2

    op1>=op2 op1 is

  • 8/4/2019 My Java Notes

    4/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    greater

    than or

    equal to

    op2

    op1 < op2

    op1 is

    less

    than to

    op2

    op1 j)); //false

    System.out.println(" j > i = " + (j > i)); //trueSystem.out.println(" k > j = " + (k > j)); //false//(they are equal)

    //greater than or equal toSystem.out.println("Greater than or equal to...");System.out.println(" i >= j = " + (i >= j)); //falseSystem.out.println(" j >= i = " + (j >= i)); //true

  • 8/4/2019 My Java Notes

    5/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    System.out.println(" k >= j = " + (k >= j)); //true

    //less thanSystem.out.println("Less than...");System.out.println(" i < j = " + (i < j)); //trueSystem.out.println(" j < i = " + (j < i)); //falseSystem.out.println(" k < j = " + (k < j)); //false

    //less than or equal toSystem.out.println("Less than or equal to...");System.out.println(" i

  • 8/4/2019 My Java Notes

    6/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    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 anArrayIndexOutOfBoundsException 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]), nowgets 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 anumber 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 anew symbol to test for equality. Java borrows C's double equals sign, ==, to test for equality. Lets lookat an example when there are more then 1 statement in a branch and how braces are usedindefinitely.Source Code

  • 8/4/2019 My Java Notes

    7/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    import java.io.*;class NumberTest{

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

    BufferedReader stdin = new BufferedReader ( newInputStreamReader( 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 thesame as ints, and ints and booleans cannot be cast back and forth. If you need to set a booleanvariable 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.ElseLets look at some examples of if-else:

    //Example 1if(a == b) {c++;}if(a != b) {c--;}

    //Example 2

  • 8/4/2019 My Java Notes

    8/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    if(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 Codepublic 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 stillonly 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:

  • 8/4/2019 My Java Notes

    9/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    //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();

  • 8/4/2019 My Java Notes

    10/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    }}

    Java Loops (while, do-while and for loops)A loop is a section of code that is executed repeatedly until a stopping condition is met. A typical loopmay look like:

    while there's more data {Read a Line of DataDo Something with the Data

    }

    There are many different kinds of loops in Java including while, for, and do while loops. Theydiffer primarily in the stopping conditions used.For loops typically iterate a fixed number of times and then exit. While loops iterate continuously

    until a particular condition is met. You usually do not know in advance how many times a while loopwill loop.In this case we want to write a loop that will print each of the command line arguments in succession,starting with the first one. We don't know in advance how many arguments there will be, but we can

    easily find this out before the loop starts using the args.length. Therefore we will write this witha for loop. Here's the code:Source Code

    // This is the Hello program in Java

    class Hello {

    public static void main (String args[]) {

    int i;

    /* Now let's say hello */System.out.print("Hello ");

    for (i=0; i < args.length; i = i++) {System.out.print(args[i]);

    System.out.print(" ");

    }System.out.println();

    }

    }We begin the code by declaring our variables. In this case we have exactly one variable, the integer

    i. iThen we begin the program by saying "Hello" just like before.

    Next comes the for loop. The loop begins by initializing the counter variable i to be zero. Thishappens exactly once at the beginning of the loop. Programming tradition that dates back to Fortraninsists that loop indices be named i, j, k, l, m and n in that order.

  • 8/4/2019 My Java Notes

    11/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    Next is the test condition. In this case we test that i is less than the number of arguments.

    When i becomes equal to the number of arguments, (args.length) we exit the loop and go to the

    first statement after the loop's closing brace. You might think that we should test for i being less thanor equal to the number of arguments; but remember that we began counting at zero, not one.Finally we have the increment step, i++ (i=i+1). This is executed at the end of each iteration of

    the loop. Without this we'd continue to loop forever since i would always be less than args.length.Java Variables and Arithmetic Expressions

    Java Variables are used to store data. Variables have type, name, and value. Variable names beginwith a character, such as x, D, Y, z. Other examples are xy1, abc2, Count, N, sum, Sum, product etc.These are all variable names.

    Different variable types are int, char, double. A variable type tells you what kind of data can be storedin that variable.

    The syntax of assignment statements is easy. Assignment statements look like this:

    variableName = expression ;

    For example:

    int x; // This means variable x can store numbers such as 2, 10, -5.

    char y; // This means variable y can store single characters 'a', 'A'.

    double z; // This means variable z can store real numbers such as10.45, 3.13411.

    The above are declarations for variables x, y and z.Important points:

    1. Note that a variable has to be declared before being used.

    2. The values assigned to a variable correspond to its type. Statements below represent assignmentof values to a variable.

    x = 100; // x is an integer variable.y = 'A'; // y is a character variable.abc = 10.45; // abc is of type double (real numbers).

    3. Both variable declaration and assignment of values can be done in same statement. For example,

    int x;x = 100; is same as int x = 100;

    4. A variable is declared only once.

    int x; // Declaration for x.

  • 8/4/2019 My Java Notes

    12/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    x = 100; // Initialization.x = x + 12; // Using x in an assignment statement.Often in a program you want to give a variable, a constant value. This can be done:

    class ConstDemo{public static void main ( String[] arg )

    {final double PI = 3.14;final double CONSTANT2 = 100;

    . . . . . .}}The reserved word final tells the compiler that the value will not change. The names of constantsfollow the same rules as the names for variables. (Programmers sometimes use all capital letters forconstants; but that is a matter of personal style, not part of the language.)

    2. Arithmetic Expressions

    --------------------------An assignment statement or expression changes the value that is held in a variable. Here is aprogram that uses an assignment statement:

    class example{

    public static void main ( String[] args ){

    long x ; //a declaration without an initial value

    x = 123; //an assignment statementSystem.out.println("The variable x contains: " + x );

    }}

    Java Arithmetic expressions use arithmetic operators such as +, -, /, *, and %. The % operator isthe remainder or modulo operator. Arithmetic expressions are used to assign arithmetic values tovariables. An expression is a combination of literals, operators, variables, and parentheses used tocalculate a value.

    The following code describes the use of different arithmetic expressions.

    int x, y, z; // Three integer variables declared at the same time.

    x = 10;y = 12;z = y / x; // z is assigned the value of y divided by x.

    // Here z will have value 1.

  • 8/4/2019 My Java Notes

    13/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    z = x + y; // z is assigned the value of x+y // Here z will have value 22.

    z = y % x // z is assigned the value of remainder when y // is divided by x. Here z will have value2.

    Java Boolean expressions are expressions which are either true or false. The different booleanoperators are < (less than), > (greater than),

    == (equal to), >= (greater or equal to), 1) // This expression checks if y is greater than 1.

    ((x - y) == (z + 1)); // This expression checks// if (x - y) equals (z + 1).

    A boolean expression can also be a combination of other boolean expressions. Two or more booleanexpressions can be connected using &&(logical AND) and || (logical OR) operators.

    The && operator represents logical AND. The expression is true only if both boolean expressions aretrue. The || operator represents logicalOR. This expression would be true if any one of the associated expressions is true.

    Example:

    int x = 10; int y = 4; int z = 5;

    (x 1) // This expression checks if x is less// than 10 AND y is greater than 1.// This expression is TRUE.

    (x*y == 41) || (z == 5) // This expression checks if x*y is equal// to 40 OR if z is equal to 5.

    // This expression is FALSEMethods (Includes Recursive Methods)

    A method is a group of instructions that is given a name and can be called up at any point in aprogram simply by quoting that name. Each calculation partof a program is called a method. Methodsare logically the same as C's functions, Pascal's procedures and functions, and Fortran's functionsand 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

  • 8/4/2019 My Java Notes

    14/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    quite a lot of code, but it is all stored for us in the System libraries. Thus rather than including thatcode every time we need to print, we just call theSystem.out.println() method.

    You can write and call your own methods too. Methods begin with a declaration. This can includethree 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 usedwithin the class where it is defined. Aprotected method can be used anywhere within the package in

    which it is defined. Methods that aren't specifically declared public or private are protected bydefault.access specifier. We then decide whether the method is or is not static. Static methods haveonly one instance per class rather than one instance per object. All objects of the same class share asingle 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

  • 8/4/2019 My Java Notes

    15/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    problem can be directly solved. Java supports recursive methods, i.e. even if you're already insidemethodA() you can call methodA().Example (A Recursive Counterpart of the Above Factorial Method)n! is defined as n times n-1 times n-2 times n-3 ... times 2 times 1 where n is a positive integer. 0! isdefined as 1. As you see n! = n time (n-1)!. This lends itself to recursive calculation, as in the followingmethod:

    public static long factorial (int n) {

    if (n < 0) {return -1;

    }

    else if (n == 0) {return 1;

    }else {

    return n*factorial(n-1);

    }

    }Arrays

    Arrays are generally effective means of storing groups of variables. An array is a group of variablesthat share the same name and are ordered sequentially from zero to one less than the number ofvariables in the array. The number of variables that can be stored in an array is called thearray's dimension. Each variable in the array is called an elementof the array.Creating Arrays

    There are three steps to creating an array, declaring it, allocating it and initializing it.

    Declaring Arrays

    Like other variables in Java, an array must have a specific type like byte, int, String or double. Onlyvariables of the appropriate type can be stored in an array. You cannot have an array that will storeboth ints and Strings, for instance.

    Like all other variables in Java an array must be declared. When you declare an array variable yousuffix the type with [] to indicate that this variable is an array. Here are some examples:int[] k;float[] yt;

    String[] names;In other words you declare an array like you'd declare any other variable except you append bracketsto the end of the variable type.Allocating ArraysDeclaring an array merely says what it is. It does not create the array. To actually create the array (orany other object) use the new operator. When we create an array we need to tell the compiler howmany elements will be stored in it. Here's how we'd create the variables declared above: new

  • 8/4/2019 My Java Notes

    16/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    k = new int[3];yt = new float[7];names = new String[50];The numbers in the brackets specify the dimension of the array; i.e. how many slots it has to holdvalues. With the dimensions above k can hold three ints, yt can hold seven floats and names can holdfifty Strings.Initializing Arrays

    Individual elements of the array are referenced by the array name and by an integer which representstheir position in the array. The numbers we use to identify them are called subscripts or indexes intothe array. Subscripts are consecutive integers beginning with 0. Thus the array k above has elementsk[0], k[1], and k[2]. Since we started counting at zero there is no k[3], and trying to access it willgenerate anArrayIndexOutOfBoundsException. subscriptsindexeskk[0]k[1]k[2]k[3]ArrayIndexOutOfBoundsExceptionYou can use array elements wherever you'd use a similarly typed variable that wasn't part of an array.

    Here's how we'd store values in the arrays we've been working with:

    k[0] = 2;k[1] = 5;k[2] = -2;yt[6] = 7.5f;names[4] = "Fred";This step is called initializing the array or, more precisely, initializing the elements of the array.Sometimes the phrase "initializing the array" would be reserved for when we initialize all the elementsof the array.

    For even medium sized arrays, it's unwieldy to specify each element individually. It is often helpful to

    use for loops to initialize the array. For instance here is a loop that fills an array with the squares ofthe numbers from 0 to 100.float[] squares = new float[101];

    for (int i=0; i

  • 8/4/2019 My Java Notes

    17/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    Two dimensional arrays are declared, allocated and initialized much like one dimensional arrays.However we have to specify two dimensions rather than one, and we typically use two nested forloops to fill the array. forThe array examples above are filled with the sum of their row and column indices. Here's some codethat would create and fill such an array:

    class FillArray {

    public static void main (String args[]) {

    int[][] M;M = new int[4][5];

    for (int row=0; row < 4; row++) {

    for (int col=0; col < 5; col++) {M[row][col] = row+col;

    }

    }

    }

    }In two-dimensional arrays ArrayIndexOutOfBounds errors occur whenever you exceed the maximumcolumn index or row index. Unlike two-dimensional C arrays, two-dimensional Java arrays are not justone-dimensional arrays indexed in a funny way.Multidimensional ArraysYou don't have to stop with two dimensional arrays. Java lets you have arrays of three, four or moredimensions. However chances are pretty good that if you need more than three dimensions in an

    array, you're probably using the wrong data structure. Even three dimensional arrays areexceptionally rare outside of scientific and engineering applications.The syntax for three dimensional arrays is a direct extension of that for two-dimensional arrays.Here's a program that declares, allocates and initializes a three-dimensional array:

    class Fill3DArray {

    public static void main (String args[]) {

    int[][][] M;

    M = new int[4][5][3];

    for (int row=0; row < 4; row++) {for (int col=0; col < 5; col++) {

    for (int ver=0; ver < 3; ver++) {M[row][col][ver] = row+col+ver;

    }

  • 8/4/2019 My Java Notes

    18/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    }}

    }

    }Example 1 : declaring and initializing 1-dimensional arrays

    An array groups elements of the same type. It makes it easy to manipulate the information containedin them.

    class Arrays1{

    public static void main(String args[]){

    // this declares an array named x with the type "array of int" and of

    // size 10, meaning 10 elements, x[0], x[1] , ... , x[9] ; the first term

    // is x[0] and the last term x[9] NOT x[10].int x[] = new int[10];

    // print out the values of x[i] and they are all equal to 0.for(int i=0; i

  • 8/4/2019 My Java Notes

    19/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    public static void main(String args[]){

    // this declares an array named fl with the type "array of int" and// initialize its elements

    float fl[] = {2.5f, 4.5f, 8.9f, 5.0f, 8.9f};

    // find the sum by adding all elements of the array fl

    float sum = 0.0f;for(int i=0; i

  • 8/4/2019 My Java Notes

    20/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    for(int i=0; i

  • 8/4/2019 My Java Notes

    21/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    System.out.println("Goodbye Cruel World!");

    }

    }

    Save this code in a single file called hellogoodbye.java in your javahtml directory, and compile it withthe command javac hellogoodbye.java. Then list the contents of the directory. You will see that thecompiler has produced two separate class files, HelloWorld.class and GoodbyeWorld.class. javachellogoodbye.java

    The second class is a completely independent program. Type java GoodbyeWorld and then

    type java HelloWorld. These programs run and execute independently of each other althoughthey exist in the same source code file.Class SyntaxUse the following syntax to declare a class in Java:

    //Contents of SomeClassName.java[ public ] [ ( abstract | final ) ] class SomeClassName [ extends SomeParentClass ] [ implementsSomeInterfaces ]{

    // variables and methods are declared within the curly braces}

    * A class can have public or default (no modifier) visibility.* It can be either abstract, final or concrete (no modifier).* It must have the class keyword, and class must be followed by a legal identifier.* It may optionally extend one parent class. By default, it will extend java.lang.Object.* It may optionally implement any number of comma-separated interfaces.* The class's variables and methods are declared within a set of curly braces '{}'.* Each .java source file may contain only one public class. A source file may contain any number ofdefault visible classes.* Finally, the source file name must match the public class name and it must have a .java suffix.

    Here is an example of a Horse class. Horse is a subclass of Mammal, and it implements the Hoofedinterface.

    public class Horse extends Mammal implements Hoofed{

    //Horse's variables and methods go here}Lets take one more example of Why use Classes and Objects. For instance let's suppose yourprogram needs to keep a database of web sites. For each site you have a name, a URL, and adescription.

    class website {

    String name;

  • 8/4/2019 My Java Notes

    22/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    String url;String description;

    }These variables (name, url and description) are called the members of the class. They tell you what aclass is and what its properties are. They are the nouns of the class. members. A class defines whatan object is, but it is not itself an object. An object is a specific instanceof a class. Thus when we

    create a new object we say we are instantiatingthe object. Each class exists only once in a program,but there can be many thousands of objects that are instances of that class.To instantiate an object in Java we use the new operator. Here's how we'd create a new web site:

    website x = new website();Once we've got a website we want to know something about it. To get at the member variables of thewebsite we can use the . operator. Website has three member variables, name, url and description,so x has three member variables as well, x.name, x.url and x.description. We can use these just likewe'd use any other String variables. For instance:

    website x = new website();x.name = "freehavaguide.com";

    x.url = "http://www.freejavaguide.com";x.description = "A Java Programming Website";

    System.out.println(x.name + " at " + x.url + " is " + x.description);1

    JAVA Tutorial - Class Declaration

    A simple Java class declaration with constructor declaration:class simple {// Constructorsimple(){p = 1;q = 2;r = 3;

    }int p,q,r;}In class declaration, you can declare methods of the class:class simple {// Constructorsimple(){

    p = 1;q = 2;r = 3;}int p,q,r;public int addNumbers(int var1, int var2, int var3){return var1 + var2 + var3;

  • 8/4/2019 My Java Notes

    23/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    }public void displayMessage(){

    System.out.println("Display Message");}

    }

    To invoke the class, you can create the new instance of the class:// To create a new instance class

    Simple sim = new Simple();// To access the methods of the class

    sim.addNumbers(5,1,2)

    // To show the result of the addNumbers

    System.out.println("The result is " + Integer.toString(addNumbers(5,1,2)));The complete listing of class declaration:class simple {// Constructor

    simple(){p = 1;q = 2;r = 3;}int p,q,r;public int addNumbers(int var1, int var2, int var3)

    {return var1 + var2 + var3;

    }public void displayMessage(){

    System.out.println("Display Message");}

    }

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

    { // To create a new instance classSimple sim = new Simple();// To show the result of the addNumbersSystem.out.println("The result is " +

    Integer.toString(addNumbers(5,1,2)));// To display messagesim.displayMessage();

  • 8/4/2019 My Java Notes

    24/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    }}

    Catching ExceptionsAn exception is a point in the code where something out of the ordinary has happened and theregular flow of the program needs to be interrupted; an exception is not necessarily an error. Amethod which has run into such a case will throw an exception using the throw(ExceptionClass)method. When an exception is thrown it must be caught by a catch statement that should sit right

    after a try statement.

    // This is the Hello program in Java

    class Hello {

    public static void main (String args[]) {

    /* Now let's say hello */

    System.out.print("Hello ");System.out.println(args[0]);

    }

    }If you run the program without giving it any command line arguments, then the runtime systemgenerates an exception something like,Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException atHello.main(C:\javahtml\Hello.java:7)

    Since we didn't give Hello any command line arguments there wasn't anything in args[0]. ThereforeJava kicked back this not too friendly error message about an "ArrayIndexOutOfBoundsException."we can fix this problem by testing the length of the array before we try to access its first element(using array.length). This works well in this simple case, but this is far from the only such potential

    problem.

    What is an Exception ?

    Let us see what happens when an exception occurs and is not handled properly

    When you compile and run the following program

    public class Test{public static void main(String str[]){int y = 0;

    int x = 1;// a division by 0 occurs here.int z = x/y;System.out.println("after didvision");

    }}

    The execution of the Test stops and this is caused by the division by zero at - x/y - an exception has

  • 8/4/2019 My Java Notes

    25/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    been thrown but has not been handled properly.

    How to handle an Exception ?

    To handle an Exception, enclose the code that is likely to throw an exception in a try block and followit immediately by a catch clause as follows

    public class Test{public static void main(String str[]){

    int y = 0;int x = 1;

    // try block to "SEE" if an exception occurstry{

    int z = x/y;System.out.println("after didvision");// catch clause below handles the// ArithmeticException generated by// the division by zero.

    } catch (ArithmeticException ae){System.out.println(" attempt to divide by 0");}System.out.println(" after catch ");

    }}

    The output of the above program is as follows

    attempt to divide by 0after catch

    the statement - System.out.println("after didvision") - is NOT executed, once an exception is thrown,the program control moves out of the try block into the catch block.The goal of exception handling is to be able to define the regular flow of the program in part of thecode without worrying about all the special cases. Then, in a separate block of code, you cover theexceptional cases. This produces more legible code since you don't need to interrupt the flow of thealgorithm to check and respond to every possible strange condition. The runtime environment isresponsible for moving from the regular program flow to the exception handlers when an exceptionalcondition arises.

    In practice what you do is write blocks of code that may generate exceptions inside try-catch blocks.You try the statements that generate the exceptions. Within your try block you are free to act as if

    nothing has or can go wrong. Then, within one or more catch blocks, you write the program logic thatdeals with all the special cases.

    To start a section of code which might fail or not follow through you start a try clause:

    try{

  • 8/4/2019 My Java Notes

    26/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    // Section of code which might fail}The try statement is needed in case of an exception. If the read fails in some way it will throw anexception of type java.io.IOException. That exception must be caught in this method, or the methodcan declare that it will continue throwing that message. Exception handling is a very powerful tool,you can use it to catch and throw exceptions and thus group all your error handling code very welland make it much more readable in larger more complex applications. After the try section there must

    exist one or more catch statements to catch some or all of the exceptions that can happen within thetry block. Exceptions that are not caught will be passed up to the next level, such as the function thatcalled the one which threw the exception, and so on. .

    try{// Section of code which might fail}catch (Exception1ThatCanHappen E){// things to do if this exception was thrown..

    }catch (Exception2ThatCanHappen E){// things to do if this exception was thrown..}Here's an example of exception handling in Java using the Hello World program above:

    Source Code

    // This is the Hello program in Javaclass ExceptionalHello {

    public static void main (String args[]) {

    /* Now let's say hello */

    try {System.out.println("Hello " + args[0]);

    }catch (Exception e) {

    System.out.println("Hello whoever you are");

    }}

    }You may or may not print an error message. If you write an exception handler and you don't expect itto be called, then by all means put a

    System.out.println("Error: " + e);This has the folowing advantages over handling your errors internally:

  • 8/4/2019 My Java Notes

    27/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    You can react to an error in custom defined way. A read error does not mean that the program should

    crash.

    You can write code with no worry about failure which will be handled by the users of your class.

    You can group your error handling code much better.

    You can make your application more transactional focused with nested try catch blocks:A simple Java code which demonstrates the exception handling in Java

    Refer to the java API document to see all exception types that can be handled in Java. Source Codepublic class excep2{

    public static void main(String args[]){

    int i =0 ;//Declare an array of stringsString Box [] = {"Book", "Pen", "Pencil"};while(i

  • 8/4/2019 My Java Notes

    28/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    Inside the main method of our program, we must declare a FileOutputStream object. In this case, wewish to write a string to the file, and so we create a new PrintStream object that takes as itsconstructor the existing FileOutputStream. Any data we send from PrintStream will now be passed tothe FileOutputStream, and ultimately to disk. We then make a call to the println method, passing it astring, and then close the connection.Source Code

    /** FileOutput* Demonstration of FileOutputStream and PrintStream classes*/

    import java.io.*;

    class FileOutput{

    public static void main(String args[]){FileOutputStream out; // declare a file output object

    PrintStream p; // declare a print stream object

    try{

    // Create a new file output stream connected to "myfile.txt"out = new FileOutputStream("myfile.txt");

    // Connect print stream to the output stream

    p = new PrintStream( out );

    p.println ("This is written to a file myFile.txt");

    p.close();

    }catch (Exception e)

    {System.err.println ("Error writing to the file myFile.txt");

    }

    }}Interactively communicating with the userProgram asking the user for their name and then prints a personalized greeting.Source Code

    import java.io.*;

    class PersonalHello {

  • 8/4/2019 My Java Notes

    29/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    public static void main (String args[])

    {

    byte name[] = new byte[100];

    int nr_read = 0;

    System.out.println("Your name Please?");try {

    nr_read = System.in.read(name);System.out.print("Hello ");

    System.out.write(name,0,nr_read);}

    catch (IOException e) {System.out.print("I did not get your name.");

    }

    }

    }In code that does any significant input or output you'll want to begin by importing all the various

    java.io classes. import.java.io.*; Most of the reading and writing you do in Java will be done withbytes. Here we've started with an array of bytes that will hold the user's name.First we print a query requesting the user's name. Then we read the user's name usingthe System.in.read() method. This method takes a byte array as an argument, and placeswhatever the user types in that byte array. Then, like before, we print "Hello." Finally we print theuser's name.The program doesn't actually see what the user types until he or she types a carriage return. This

    gives the user the chance to backspace over and delete any mistakes. Once the return key ispressed, everything in the line is placed in the array.

    Reading NumbersOften strings aren't enough. A lot of times you'll want to ask the user for a number as input. All userinput comes in as strings so we need to convert the string into a number. The getNextInteger() method that will accept an integer from the user. Here it is:static int getNextInteger() {

    String line;

    DataInputStream in = new DataInputStream(System.in);try {line = in.readLine();int i = Integer.valueOf(line).intValue();return i;

    }catch (Exception e) {

  • 8/4/2019 My Java Notes

    30/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    return -1;}

    } // getNextInteger ends hereReading Formatted DataIt's often the case that you want to read not just one number but multiple numbers. Sometimes youmay need to read text and numbers on the same line. For this purpose Java provides the

    StreamTokenizer class.Writing a text fileSometimes you want to save your output in a file. To do this we'll need to learn how to write data to afile.Source Code

    // Write the Fahrenheit to Celsius table in a file

    import java.io.*;

    class FahrToCelsius {

    public static void main (String args[]) {

    double fahr, celsius;

    double lower, upper, step;

    lower = 0.0; // lower limit of temperature tableupper = 300.0; // upper limit of temperature table

    step = 20.0; // step size

    fahr = lower;

    try {

    FileOutputStream fout = new FileOutputStream("test.out");

    // now to the FileOutputStream into a PrintStream

    PrintStream myOutput = new PrintStream(fout);

    while (fahr

  • 8/4/2019 My Java Notes

    31/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    }

    } // main ends here

    }There are only three things necessary to write formatted output to a file rather than to the standardoutput:

    1. Open a FileOutputStreamusing a line like

    FileOutputStream fout = new FileOutputStream("test.out");

    This line initializes the FileOutputStream with the name of the file you want to write into.

    2. Convert the FileOutputStream into a PrintStreamusing a statement like

    PrintStream myOutput = new PrintStream(fout);

    The PrintStream is passed the FileOutputStream from step 1.

    3. Instead of

    using System.out.println() use myOutput.println(). System.out and myOutput ar

    e just different instances of the PrintStream class. To print to a different PrintStream we

    keep the syntax the same but change the name of the PrintStream.Reading a text fileNow that we know how to write a text file, let's try reading one. The following code accepts a series offile names on the command line and then prints those filenames to the standard output in the orderthey were listed.

    // Imitate the Unix cat utility

    import java.io.*;

    class cat {

    public static void main (String args[]) {

    String thisLine;

    //Loop across the argumentsfor (int i=0; i < args.length; i++) {

    //Open the file for reading

    try {

    FileInputStream fin = new FileInputStream(args[i]);

    // now turn the FileInputStream into a DataInputStreamtry {

    DataInputStream myInput = new DataInputStream(fin);

    try {

  • 8/4/2019 My Java Notes

    32/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    while ((thisLine = myInput.readLine()) != null) { // while loop begins hereSystem.out.println(thisLine);

    } // while loop ends here}catch (Exception e) {

    System.out.println("Error: " + e);}

    } // end trycatch (Exception e) {

    System.out.println("Error: " + e);}

    } // end try

    catch (Exception e) {System.out.println("failed to open file " + args[i]);

    System.out.println("Error: " + e);}

    } // for end here

    } // main ends here

    }How to make executable jar files in JDK1.3.1?

    Instructions for creating an Executable .jar fileMake or modify the Manifest.MF to YourManifest.MF.

    1) YourClassNameWithMain is the class name (case sensitive) without .class extension2) No extra spaces following the YourClassName withMain.

    Manifest-Version:1.0Main-Class: YourClassNameWithMainCreated-by:1.2(Sun Microsystems Inc.)On Command line : type the following

    jar cvfm YourJarFileName.jar YourManifest.MF*

    or

    jar cvfm YourJarFileName.jar YourManifest.MF -C classes yourClassPathDrag-drop the YourJarFileName.jar to your desktop double click it, it runs

    If your program only has System.out.println ("whatever"); statements, it willdisplay nothing. The same will happen when you run it useing java at command lineYou need some windows code to see it run

    Instructions for creating a .jar file. jar utility comes with your JDK1.2.2 It compresses your file similarto zip utility, and more Java.

  • 8/4/2019 My Java Notes

    33/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    You can use it on any machine installed JDKCreate a folder name it anythingMake that folder your current directoryput all your files for turning in (do not put any extra) in that directory.

    Be sure to put your html file, if there is one

    At your dos prompt, while you are in the directory that you created , type in:jar cvf Prj02.jar*This will take ALL the files in the directory including subdirectories and place them in a .jar file Prj02that can be replaced by any of your desired jar file name.

    To test it, you can extract the contents of jar file by typing:jar xvf Prj02.jar

  • 8/4/2019 My Java Notes

    34/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    Program 1//Find Maximum of 2 nos.class Maxof2{

    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]);

    if(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 operatorclass 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 = (i

  • 8/4/2019 My Java Notes

    35/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    System.out.println(result+" is a minimum value");

    }

    }

    Program 3/* Write a program that will read a float type value from the keyboard and print the followingoutput.

    ->Small 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;i

  • 8/4/2019 My Java Notes

    36/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    }

    Program 5/* Write a program to display a greet message according to

    Marks obtained by student.*/

    class SwitchDemo{

    public static void main(String args[]){

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

    switch(marks/10){

    case 10:

    case 9:

    case 8:

    System.out.println("Excellent");

    break;

    case 7:

    System.out.println("Very Good");

    break;

    case 6:

    System.out.println("Good");

    break;

    case 5:

    System.out.println("Work Hard");

    break;

  • 8/4/2019 My Java Notes

    37/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    case 4:

    System.out.println("Poor");

    break;

    case 3:

    case 2:

    case 1:

    case 0:

    System.out.println("Very Poor");

    break;

    default:

    System.out.println("Invalid value Entered");

    }

    }

    }

    Program 6/*Write a program to find SUM AND PRODUCT of a given Digit. */class Sum_Product_ofDigit{

    public static void main(String args[]){

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

    int temp = num,result=0;

    //Logic for sum of digit

    while(temp>0){

  • 8/4/2019 My Java Notes

    38/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    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;

  • 8/4/2019 My Java Notes

    39/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    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 - 8Output - 1 1 2 3 5 8 13 21

  • 8/4/2019 My Java Notes

    40/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    */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

  • 8/4/2019 My Java Notes

    41/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    }

    System.out.println("Output of Program is : "+result);

    }

    }

    Program 11

    /* Write a program to Concatenate string using for Loop

    Example:Input - 5Output - 1 2 3 4 5 */

    class Join{

    public static void main(String args[]){

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

    String result = " ";

    for(int i=1;i

  • 8/4/2019 My Java Notes

    42/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    System.out.println("*****MULTIPLICATION TABLE*****");

    for(int i=1;i

  • 8/4/2019 My Java Notes

    43/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    System.out.println("\n***After Swapping***");

    System.out.println("Number 1 : "+num1);

    System.out.println("Number 2 : "+num2);

    }

    }

    Program 14/* Write a program to convert given no. of days into months and days.(Assume that each month is of 30 days)Example :

    Input - 69Output - 69 days = 2 Month and 9 days */

    class DayMonthDemo{

    public static void main(String args[]){

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

    int days = num%30;

    int month = num/30;

    System.out.println(num+" days = "+month+" Month and "+days+" days");

    }

    }

    Program 15/*Write a program to generate a Triangle.

    eg:

    1

    2 2

  • 8/4/2019 My Java Notes

    44/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    3 3 3

    4 4 4 4 and so on as per user given number */

    class Triangle{

    public static void main(String args[]){

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

    for(int i=1;i

  • 8/4/2019 My Java Notes

    45/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    while(num > 0){

    for(int j=1;j 0){

    remainder = num % 10;

    check = check + (int)Math.pow(remainder,3);

    num = num / 10;

    }

  • 8/4/2019 My Java Notes

    46/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    if(check == n)

    System.out.println(n+" is an Armstrong Number");

    else

    System.out.println(n+" is not a Armstrong Number");

    }

    }

    Program 18/* Write a program to Find whether number is Prime or Not. */ class PrimeNo{

    public static void main(String args[]){

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

    int flag=0;

    for(int i=2;i

  • 8/4/2019 My Java Notes

    47/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    }

    }

    Program 19/* Write a program to find whether no. is palindrome or not.

    Example :Input - 12521 is a palindrome no.Input - 12345 is not a palindrome no. */

    class Palindrome{

    public static void main(String args[]){

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

    int n = num; //used at last time check

    int reverse=0,remainder;

    while(num > 0){

    remainder = num % 10;

    reverse = reverse * 10 + remainder;

    num = num / 10;

    }

    if(reverse == n)

    System.out.println(n+" is a Palindrome Number");

    else

    System.out.println(n+" is not a Palindrome Number");

    }

    }

    Program 20

  • 8/4/2019 My Java Notes

    48/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    /* switch case demoExample :

    Input - 124Output - One Two Four */

    class SwitchCaseDemo{

    public static void main(String args[]){

    try{

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

    int n = num; //used at last time check

    int reverse=0,remainder;

    while(num > 0){

    remainder = num % 10;

    reverse = reverse * 10 + remainder;

    num = num / 10;

    }

    String result=""; //contains the actual output

    while(reverse > 0){

    remainder = reverse % 10;

    reverse = reverse / 10;

    switch(remainder){

    case 0 :

    result = result + "Zero ";

  • 8/4/2019 My Java Notes

    49/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    break;

    case 1 :

    result = result + "One ";

    break;

    case 2 :

    result = result + "Two ";

    break;

    case 3 :

    result = result + "Three ";

    break;

    case 4 :

    result = result + "Four ";

    break;

    case 5 :

    result = result + "Five ";

    break;

    case 6 :

    result = result + "Six ";

    break;

    case 7 :

    result = result + "Seven ";

  • 8/4/2019 My Java Notes

    50/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    break;

    case 8 :

    result = result + "Eight ";

    break;

    case 9 :

    result = result + "Nine ";

    break;

    default:

    result="";

    }

    }

    System.out.println(result);

    }catch(Exception e){

    System.out.println("Invalid Number Format");

    }

    }

    }

    Program 21/* Write a program to generate Harmonic Series.Example :

    Input - 5Output - 1 + 1/2 + 1/3 + 1/4 + 1/5 = 2.28 (Approximately) */

    class HarmonicSeries{

    public static void main(String args[]){

  • 8/4/2019 My Java Notes

    51/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

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

    double result = 0.0;

    while(num > 0){

    result = result + (double) 1 / num;

    num--;

    }

    System.out.println("Output of Harmonic Series is "+result);

    }

    }

    Program 22/*Write a program to find average of consecutive N Odd no. and Even no. */ class EvenOdd_Avg{

    public static void main(String args[]){

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

    int cntEven=0,cntOdd=0,sumEven=0,sumOdd=0;

    while(n > 0){

    if(n%2==0){

    cntEven++;

    sumEven = sumEven + n;

    }

    else{

    cntOdd++;

  • 8/4/2019 My Java Notes

    52/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    sumOdd = sumOdd + n;

    }

    n--;

    }

    int evenAvg,oddAvg;

    evenAvg = sumEven/cntEven;

    oddAvg = sumOdd/cntOdd;

    System.out.println("Average of first N Even no is "+evenAvg);

    System.out.println("Average of first N Odd no is "+oddAvg);

    }

    }

    Program 23

    /* Display Triangle as follow : BREAK DEMO.12 34 5 67 8 9 10 ... N */

    class Output1{

    public static void main(String args[]){

    int c=0;

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

    loop1: for(int i=1;i

  • 8/4/2019 My Java Notes

    53/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    if(c!=n){

    c++;

    System.out.print(c+" ");

    }

    else

    break loop1;

    }

    System.out.print("\n");

    }

    }

    }

    Program 24/* Display Triangle as follow

    0

    1 01 0 10 1 0 1 */

    class Output2{

    public static void main(String args[]){

    for(int i=1;i

  • 8/4/2019 My Java Notes

    54/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    }

    }

    }

    Program 25

    /* Display Triangle as follow12 43 6 94 8 12 16 ... N (indicates no. of Rows) */

    class Output3{

    public static void main(String args[]){

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

    for(int i=1;i

  • 8/4/2019 My Java Notes

    55/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    You specify which Calendar field is to be affected by the operation(Calendar.YEAR, Calendar.MONTH, Calendar.DATE).*/

    public static void addToDate(){System.out.println("In the ADD Operation");

    // String DATE_FORMAT = "yyyy-MM-dd";String DATE_FORMAT = "dd-MM-yyyy"; //Refer Java DOCS

    for formatsjava.text.SimpleDateFormat sdf = new

    java.text.SimpleDateFormat(DATE_FORMAT);Calendar c1 = Calendar.getInstance();Date d1 = new Date();System.out.println("Todays date in Calendar Format : "+c1);System.out.println("c1.getTime() : "+c1.getTime());System.out.println("c1.get(Calendar.YEAR): " +

    c1.get(Calendar.YEAR));System.out.println("Todays date in Date Format : "+d1);c1.set(1999,0 ,20); //(year,month,date)

    System.out.println("c1.set(1999,0 ,20) : "+c1.getTime());c1.add(Calendar.DATE,40);System.out.println("Date + 20 days is : " +

    sdf.format(c1.getTime()));System.out.println();System.out.println();

    }

    /*Substract Day/Month/Year to a Dateroll() is used to substract values to a Calendar object.You specify which Calendar field is to be affected by the operation(Calendar.YEAR, Calendar.MONTH, Calendar.DATE).

    Note: To substract, simply use a negative argument.roll() does the same thing except you specify if you want to roll up

    (add 1)or roll down (substract 1) to the specified Calendar field. The

    operation onlyaffects the specified field while add() adjusts other Calendar fields.See the following example, roll() makes january rolls to december in

    the sameyear while add() substract the YEAR field for the correct result

    */

    public static void subToDate(){System.out.println("In the SUB Operation");String DATE_FORMAT = "dd-MM-yyyy";java.text.SimpleDateFormat sdf = new

    java.text.SimpleDateFormat(DATE_FORMAT);

  • 8/4/2019 My Java Notes

    56/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    Calendar c1 = Calendar.getInstance();c1.set(1999, 0 , 20);System.out.println("Date is : " + sdf.format(c1.getTime()));

    // roll down, substract 1 monthc1.roll(Calendar.MONTH, false);System.out.println("Date roll down 1 month : " +

    sdf.format(c1.getTime()));

    c1.set(1999, 0 , 20);System.out.println("Date is : " + sdf.format(c1.getTime()));c1.add(Calendar.MONTH, -1);// substract 1 monthSystem.out.println("Date minus 1 month : " +

    sdf.format(c1.getTime()));System.out.println();System.out.println();

    }

    public static void daysBetween2Dates(){Calendar c1 = Calendar.getInstance(); //new

    GregorianCalendar();Calendar c2 = Calendar.getInstance(); //new

    GregorianCalendar();c1.set(1999, 0 , 20);c2.set(1999, 0 , 22);System.out.println("Days Between "+c1.getTime()+"\t"+

    c2.getTime()+" is");System.out.println((c2.getTime().getTime() -

    c1.getTime().getTime())/(24*3600*1000));System.out.println();

    System.out.println();}

    public static void daysInMonth() {Calendar c1 = Calendar.getInstance(); //new

    GregorianCalendar();c1.set(1999, 6 , 20);int year = c1.get(Calendar.YEAR);int month = c1.get(Calendar.MONTH);

    // int days = c1.get(Calendar.DATE);

    int [] daysInMonths = {31,28,31,30,31,30,31,31,30,31,30,31};daysInMonths[1] += DateUtility.isLeapYear(year) ? 1 : 0;System.out.println("Days in "+month+"th month for year

    "+year+" is "+ daysInMonths[c1.get(Calendar.MONTH)]);System.out.println();

    System.out.println();}

  • 8/4/2019 My Java Notes

    57/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    public static void getDayofTheDate() {Date d1 = new Date();String day = null;

    DateFormat f = new SimpleDateFormat("EEEE");try {day = f.format(d1);}

    catch(Exception e) {e.printStackTrace();

    }System.out.println("The dat for "+d1+" is "+day);System.out.println();

    System.out.println();}

    public static void validateAGivenDate() {String dt = "20011223";String invalidDt = "20031315";

    String dateformat = "yyyyMMdd";Date dt1=null , dt2=null;try {

    SimpleDateFormat sdf = newSimpleDateFormat(dateformat);

    sdf.setLenient(false);dt1 = sdf.parse(dt);dt2 = sdf.parse(invalidDt);System.out.println("Date is ok = " + dt1 + "(" + dt +

    ")");}catch (ParseException e) {

    System.out.println(e.getMessage());}catch (IllegalArgumentException e) {

    System.out.println("Invalid date");}

    System.out.println();System.out.println();

    }

    public static void compare2Dates(){SimpleDateFormat fm = new SimpleDateFormat("dd-MM-yyyy");

    Calendar c1 = Calendar.getInstance();Calendar c2 = Calendar.getInstance();

    c1.set(2000, 02, 15);c2.set(2001, 02, 15);

    System.out.print(fm.format(c1.getTime())+" is ");if(c1.before(c2)){

  • 8/4/2019 My Java Notes

    58/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    System.out.println("less than "+c2.getTime());}else if(c1.after(c2)){

    System.out.println("greater than "+c2.getTime());}else if(c1.equals(c2)){

    System.out.println("is equal to"+fm.format(c2.getTime()));

    }

    System.out.println();System.out.println();

    }

    public static boolean isLeapYear(int year){if((year%100 != 0) || (year%400 == 0)){

    return true;}return false;

    }

    public static void main(String args[]){addToDate();subToDate();daysBetween2Dates(); //The "right" way would be to

    compute the julian day number of both dates and then do the substraction.daysInMonth();validateAGivenDate();compare2Dates();getDayofTheDate();

    }

    }String Utility/** NumberUtility.java** Source: http://www.freejavaguide.com*/

    import java.math.BigDecimal;import java.text.DecimalFormat;import java.text.DecimalFormatSymbols;import java.util.Locale;

    /*** Class provides common functions on number formats.*/

    public class NumberUtility {

  • 8/4/2019 My Java Notes

    59/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    /*** Method takes Object as parameter and returns decimal number.* if argument is float or double and contains tailing zeros* it removes them. If argument is float or double then no change in

    return type.* Change the Format of the Number by changing the String Pattern*/

    public static String changeToDecimalFormat(Object number) {

    BigDecimal bdNumber = new BigDecimal(number.toString());bdNumber = bdNumber.stripTrailingZeros(); //Returns a

    BigDecimal with any trailing zero's removedString pattern = "###,##0.0###########"; //To apply

    formatting when the number of digits in input equals the patternDecimalFormat newFormat = new DecimalFormat(pattern, new

    DecimalFormatSymbols(Locale.US));return newFormat.format(bdNumber);

    }

    /* Method takes Object as parameter and removes commas from theparameter */

    public static double removeCommasFromNumber(Object number) {try {

    StringBuffer inputNo = new StringBuffer(number.toString());if (inputNo.length() > 0) {

    while (inputNo.indexOf(",") != -1) {inputNo.deleteCharAt(inputNo.indexOf(","));

    }} else {

    return 0.0;}return Double.parseDouble(inputNo.toString());

    } catch (NumberFormatException e) {return 0.0;

    }}

    /* Some times its required to have a fixed set of decimal places for a* number. We can set that by changing the precision number for a

    particular* input BigDecimal Input String*/public static String changeToRequiredDecimals(String bigDecimalString,

    int precision) {String newFormattedString = null;String afterDecimal = null;if (bigDecimalString == null || bigDecimalString.length() == 0) {

  • 8/4/2019 My Java Notes

    60/61

    CORE JAVA NOTES

    YOGESH SIR

    Mob: 8896513100

    Email : [email protected]

    return "0.0";}if (bigDecimalString.contains(".")) {

    afterDecimal = bigDecimalString.substring(bigDecimalString.indexOf(".") + 1);

    int length = Math.abs((afterDecimal.length() - precision));if (afterDecimal.length() < precision) {

    newFormattedString = bigDecimalString;for (int i = 0; i < length; i++) {

    newFormattedString = newFormattedString + "0";}

    } else if (afterDecimal.length() > precision) {newFormattedString = bigDecimalString.substring(0,

    bigDecimalString.length() - length);if (precision == 0) {

    newFormattedString = newFormattedString.substring(0,newFormattedString.indexOf("."));

    } else {

    newFormattedString = bigDecimalString;}

    } else {if (precision > 0)

    newFormattedString = bigDecimalString + ".";else

    newFormattedString = bigDecimalString;for (int i = 0; i < precision; i++) {

    newFormattedString = newFormattedString + "0";}

    }}return newFormattedString;

    }

    public static void main(String args[]){int intVar = 10;double doubleVar = 10.504000;float floatVar = 343534534348.5687654F;String commaString = "343,534,535,000.0";BigDecimal bdNumber = new BigDecimal("1234.8765");

    System.out.println(NumberUtility.changeToDecimalFormat(newInteger(intVar)));

    System.out.println(NumberUtility.changeToDecimalFormat(newDouble(doubleVar)));

    System.out.println(NumberUtility.changeToDecimalFormat(newFloat(floatVar)));

  • 8/4/2019 My Java Notes

    61/61

    CORE JAVA NOTES

    System.out.println(NumberUtility.removeCommasFromNumber(commaString));

    System.out.println(NumberUtility.changeToRequiredDecimals(bdNumber.toString(), 8));

    }}