Showing posts with label Java Utilities. Show all posts
Showing posts with label Java Utilities. Show all posts

Spring Framework Generate Random Integer in specific range in Java

Ranging random integers not found in java.util.Random


An example on generating random integers between a specified range.


Example


import java.util.*;
class RandomRangeInt
{
public static void main(String args[])
{

// Create Random object
Random r=new Random();

// Specify start, end
int start=10;
int end=100;

// Create a 1 time loop
for(int i=0;i<1;i++)
{

// Generate random int below 100
int k=r.nextInt(end);

// If random integer below 100 is greater than start (10)
                        if(k>start)

// Then print
System.out.println(k);

                        // Else loop again, till if is true!, you may also write while loop
else i--;

}
}
}

Output

77

If you want to include start i.e. you want to allow even value of start (here 10) to come, then you must change if(k>start) to if(k>=start)

If you don't wish to write the logic, you can see my example on my class gowtham.gutha.util.RandomRangeInteger, download the java-utils framework (for using the class).

If you don't have already seen generating random integers in Java, you can see my post of Generating random values in Java (for all datatypes int,float,long,double..) and for generating random strings from first and last names, there is also a post.

Spring Framework How to reverse elements in ArrayList

Reverse elements in ArrayList
Here i will discuss about reversing elements in a List. The method used here works for all implementations of the java.util.List which include ArrayList, LinkedList and Vector classes. There is no logic that we need to write to reverse the elements. The method reverse(List) has done everything for us and we are just a method call away from it. Simple is that. This method is present in the java.util.Collections class and is available as static which means that it can be accessed without the need of creating an object. The order of the elements in the list is reversed. Here is a tiny example that illustrates this.


import java.util.*;
class ReverseList
{
    public static void main(String args[])
    {

    // Create an ArrayList containing String type elements

    ArrayList<String> aList=new ArrayList<String>();


    // Add elements to the ArrayList aList   

    aList.add("Gowtham");
    aList.add("Gutha's");
    aList.add("java");
    aList.add("-");
    aList.add("demos");
    aList.add(".");
    aList.add("blogspot");
    aList.add(".");
    aList.add("com");

    // Store the size of aList
    // This avoids repeated calling of method in loops

    int size=aList.size();

    // Print elements before reversing


    System.out.println("\nElements before reversing");
   
    System.out.println("--------------------");


        for(int i=0;i<size;i++)
        {
        System.out.println(aList.get(i));
        }   


   
    // Reverse the elements in ArrayList

    Collections.reverse(aList);


    // Print the reversed elements

    System.out.println("\nElements in reversed order");

    System.out.println("--------------------");


        for(int i=0;i<size;i++)
        {
        System.out.println(aList.get(i));
        }   


    }
}

Output of the program



Elements before reversing
--------------------
Gowtham
Gutha's
java
-
demos
.
blogspot
.
com

Elements in reversed order
--------------------
com
.
blogspot
.
demos
-
java
Gutha's
Gowtham

Explaining the program

There is nothing in fact to explain in the program except the method which does it all. The java.util.Collections.sort(List l) method takes in a java.util.List object (i.e. object of any of it's implementing classes) and sorts it. In a similar way you can do it for LinkedList and Vector also. Just Replace All ArrayList with LinkedList (for LinkedList) and with Vector (for Vector), Stack. That's it.

Also see my post on sorting elements in a ArrayList, LinkedList and Vector

Spring Framework Sort Elements in ArrayList, LinkedList, Vector

Sorting elements in ArrayList, LinkedList and Vector
Let us sort elements in ArrayList in the increasing order. Not only ArrayList, but also LinkedList. The code for both of them is same and dead easy as well. All you need to do is to remember this sweet method prototype. The following method will sort the elements according to their compareTo() method. For elements in a list to be sorted, those elements must be implementing the java.lang.Comparable interface.


import java.util.*;
class SortList
{
    public static void main(String args[])
    {

    // Create an ArrayList containing String type elements

    ArrayList<String> aList=new ArrayList<String>();


    // Add elements to the ArrayList aList  

    aList.add("Gowtham");
    aList.add("Gutha's");
    aList.add("java");
    aList.add("-");
    aList.add("demos");
    aList.add(".");
    aList.add("blogspot");
    aList.add(".");
    aList.add("com");


    // Print elements before sorting

    System.out.println("\nElements before sorting");
    System.out.println("--------------------");

        for(int i=0;i<aList.size();i++)
        {
        System.out.println(aList.get(i));
        }  


   
    // Sort the elements in ArrayList

    Collections.sort(aList);


    // Print the sorted elements

    System.out.println("\nElements in sorted order");
    System.out.println("--------------------");


        for(int i=0;i<aList.size();i++)
        {
        System.out.println(aList.get(i));
        }  


    }
}

Output of the program




Elements before sorting
--------------------
Gowtham
Gutha's
java
-
demos
.
blogspot
.
com

Elements in sorted order
--------------------
-
.
.
Gowtham
Gutha's
blogspot
com
demos
java

Explaining the program

The java.util.Collections class contains a static method called sort() which takes a java.util.List object and sorts this according to the compareTo() method written in the element class. Here, the elements are of type java.lang.String and hence for sorting the compareTo() method in the String class is used. As said earlier, for this to happen the element class must be implementing the java.lang.Comparable interface. The algorithm used for developing this method is a modified version of the mergesort.

The List that is sent as parameter should be modifiable because re arranging the elements has to take place.
To sort a LinkedList the way is the same. To try the above program with LinkedList Replace All the ArrayList with LinkedList and for Vector replace with Vector. Save the program, compile and then execute. That's it. Remember that the Collections.sort() takes List object which can be LinkedList or ArrayList or Vector and any class implementing the List interface.

Also see sorting an array in increasing order

Spring Hibernate Generate Random String in Java

Random String Generation in Java


Yet another example on generating a random string in Java taking characters randomly from first and last names and attaching a random number <1000 at the end.


Example


// For Scanner and Random classes
import java.util.*;
class GenerateRandomName
{
public static void main(String args[])
{

// Create a java.util.Scanner object for taking input from cmd
Scanner s=new Scanner(System.in);

// Take first name
String fname=s.nextLine();

// Take last name
String lname=s.nextLine();

// Create java.util.Random object
Random r=new Random();

// Generate random name
String rname=fname.substring(0,r.nextInt(fname.length()-1))+lname.substring(0,r.nextInt(lname.length()-1))+r.nextInt(10000);

// Print random name
System.out.println("Random name: "+rname);

}
}

Output


Gowtham
Gutha
Random name: GowGut2446


The theme of generation is explained above. For further doubts, feel free to drop a comment.

Also see Generating Random numbers in Java

Spring Framework Difference between capacity() and size() in Vector

The difference between capacity() and size() in java.util.Vector is that capacity() returns how many elements it can store whereas the size() gives the no.of elements in the Vector at the time of method call.
Capacity of a vector is usually declared within the constructor itself. An example will give better understand.



import java.util.*;


class CapacitySize


{


public static void main(String args[])


{


Vector<String> v=new Vector<String>(10);


v.setSize(3);


v.add("java-demos.blogspot.com");


v.add("Gowtham Gutha");




System.out.println("The capacity of the vector is "+v.capacity());


System.out.println("The size of the vector is "+v.size());


}


}


In the above example, the size of the vector is set to 10 (if you use the default constructor, the default vector size then will be 10 only). Next, the size is set to 3 and then added 2 elements to it. When, the size is printed, 5(3+2) is printed. Because 2 elements are added after the size is set to 3. A vector is like a dynamic array which can be extended. The capacity is the no.of elements that the vector can store is 10 because 10 is passed in the creation, 10 will be printed.

Sample Output



The capacity of the vector is 10


The size of the vector is 5

92YF2PBFC8XG

Spring Framework Remove Duplicate Elements in a Vector

Remove Duplicates in a Vector
Vector in java.util package is used as a dynamic array. Any no.of elements can be added to the vector. It might be essential sometimes to remove duplicate elements in the vector to save space. While this is not needed all the time, it is better to have an idea about the logic of how to remove duplicate elements in a Vector. Let us see how we can do this.





import java.util.*;

class RemoveDuplicates

{



    public static void main(String args[])

    {

    Vector<String> v=new Vector<String>();

    v.add("Gowtham");

    v.add(" Gutha's");

    v.add(" Java");

    v.add("-");

    v.add("demos");

    v.add(".");

    v.add("blogspot");



    // '.' again!

    v.add(".");

    v.add("com ");



    // Gowtham again!

    v.add("gowtham");

       

    System.out.println("Original");



        for(int i=0;i<v.size();i++)

        {

            System.out.print(v.elementAt(i));



        }



    System.out.println("\nAfter removing duplicates");

    removeDuplicates(v);



        for(int i=0;i<v.size();i++)

        {

            System.out.print(v.elementAt(i));

        }

   

    }





    // Applicable for all types of vectors



    public static void removeDuplicates(Vector v)

    {

        for(int i=0;i<v.size();i++)

        {

            for(int j=0;j<v.size();j++)

            {

                    if(i!=j)

                    {

                        if(v.elementAt(i).equals(v.elementAt(j)))

                        {

                        v.removeElementAt(j);

                        }

                    }

            }

        }

    }





    /*

        * Specifically applicable for String is written for equalIgnoreCase

        * The code..

   



        public static void removeDuplicates(Vector<String> v)

        {

            for(int i=0;i<v.size();i++)

            {

                for(int j=0;j<v.size();j++)

                {

                    if(i!=j)

                    {

                        if(v.elementAt(i).equalsIgnoreCase(v.elementAt(j)))

                        {

                        v.removeElementAt(j);

                        }

                    }

            }

        }

    */



}

Output



Original

Gowtham Gutha's Java-demos.blogspot.com gowtham

After removing duplicates

Gowtham Gutha's Java-demos.blogspotcom gowtham

Logic Analysis


A. Logic Applicable for all types of vectors

This is the logic that can be used for any type of Vector. java.util.Vector is a generic class and therefore any type of object can be stored. The equals() method compares two objects. It returns true if the object values are equal, false otherwise.
A double loop is used here which checks each element in the array at one index with other index. For a better understand, lets consider a case.
At the statement,
for(int i=0;i<v.size();i++)
The initial value of i is 0 and it is looped till it reaches v.size()-1 (This is because the elements are stored in the vector from 0th element and not from 1st element). v.size() returns the size of the vector i.e. number of elements in the vector. The i value increments every time the loop is executed. This is done till the condition of the loop fails i.e. i value equals to the size of the vector.

The next loop is the inner loop which consists of the same code but with i replaced by j.

A.1 Now what do the loops do?

The loops are used to check an element at particular index with other elements at other indexes and also the same element at the same index. Didn't get it? No problem. I'll explain analytically using the program.

First when i=0 and when control enters the inner for loop, then, j=0. The condition, if(i!=j) means that if the value of i is not equal to j. So control enters the inner if condition only if the value of i does not match with j. Next time, when the inner for loop (j loop) executes, the value of j becomes 1 due to j++ and the condition is i!=j is passed since i=0 and j=1 and now the control enters the inner most if condition and checks whether the element at i (here 0) is equal to the element at j (here j=1) which means that if first element (i.e. element at 0th index) is equal to the second element (i.e. element at the 1st index). This process continues till the inner for loop condition fails i.e. the value of j becomes the size of the vector. In all the cases (here) except 0 the outer if condition (i!=j condition) is satisfied and control enters the inner condition. If this condition is satisfied, then the element at j is removed. Here we are removing the elements that are repeated and at the positions after which they had already occurred. For example, if gowtham is an element that is repeated which occurs at 0th position in the vector and also at the fourth position in the vector, then the gowtham at the fourth position is removed not the one at the first position (i.e. not the one that has occurred first).
So whenever the i and j values never coincide (i.e. whenever they are not equal) and whenever the element at i position is equal to the element at j position, then the element at j position is removed.

i=0 and j=0; i!=j (false)
i=0 and j=1; i!=j (true) -> Check the inner if condition -> Remove duplicate if satisfied
i=0 and j=2; i!=j (true) -> Check the inner if condition -> Remove duplicate if satisfied
....

So, if we consider the 0th element is checked with 1st element, 2nd element, 3rd element, 4th element and so on till the end of all the elements in the vector. It is removed when it is found to be a duplicate.

Similarly,  1st element is checked with 0th element, 2nd element,3rd element, 4th element.... with all the elements in the vector to ensure that whether it is repeated or not.

Similarly, 2nd element is checked with 0th element, 1st element, 2nd element, 3rd element....

You'll have to note that the element 0th element is not checked with 0th element because they are however equal and in a similar way, 1st element is not checked with 1st element because they are however similar. This checking is prevented by i!=j condition. So, therefore the duplicate elements are removed.

B. Logic applicable for String type vectors only

With the help of this logic String type vectors can be ignored. You might already have an idea about equalIgnoreCase() method. It compares two strings ignoring the case. For example, java and Java are both equal according to equalIgnoreCase().

Spring Framework Binary search for integer in array

The following example illustrates binary search of int in array.

import java.util.*;

class SearchInt

{

public static void main(String args[])

{

Scanner s=new Scanner(System.in);

System.out.println("Enter no.of elements");

int n=s.nextInt();



System.out.println("Enter elements into array");

int[] a=new int[n];



for(int i=0;i<n;i++)

{

a[i]=s.nextInt();

}



System.out.println("Enter search element");

int sr=s.nextInt();



Arrays.sort(a);



System.out.println("Sorted array\n--------------");

for(int k:a)

System.out.println(k);



int idx=Arrays.binarySearch(a,sr);



System.out.println("Element found at (after sorting) "+idx);

}

}

Sample Output




Enter no.of elements


8


Enter elements into array


6


9


8


7


5


6


45


45


Enter search element


8


Sorted array


--------------


5


6


6


7


8


9


45


45


Element found at (after sorting)  4



binarySearch(a,sr): Takes array and search element respectively. Static method of the class.
sort(a): a must be sorted before searching for proper results. Static method.
idx: The index (may be any index if repeated more than 1 time). index value is with respect to the sorted array and not to the original one.
Arrays: Located in the java.util package.

Spring Framework How to Convert ArrayList into Array

Here is a question about converting ArrayList to an array. We can do this using two simple methods in the java.util.ArrayList. These methods return the Object[] which can be typecasted. Here are two programs that illustrate two methods separately for a better understand. These are provided with explanation and analysis for help. Not only this you'll learn a lot of things in this post (bonus!)


import java.util.*;
class ArrayListToArray
{
    public static void main(String args[])
    {
    ArrayList<String> a=new ArrayList<String>();

    a.add("Gowtham");
    a.add("Gutha's");
    a.add("Java");
    a.add("-");
    a.add("demos");
    a.add(".");
    a.add("blogspot");
    a.add(".");
    a.add("com");

    String st[]=a.toArray(new String[a.size()]);
   
    System.out.println("The elements are");

        for(String k:st)
        System.out.println(k);
    }
}



Output of the Program



The elements are
Gowtham
Gutha's
Java
-
demos
.
blogspot
.
com



Explaining toArray(T[]) method

This method returns an array of type of the object of ArrayList elements which is also the type of this method's parameter. For example, as you can see in the above program, i have sent new String[a.size()] as parameter and the elements in the ArrayList are of type String. So as there are multiple elements of type String we'll get a String[] in return. This returned String[] contains all the elements in the ArrayList in the order. This method is created for generic types. The parameter T[] clearly expresses this.
If you try changing the type of the parameter and the return type such as specifying the type of the parameter as an Integer array and the return type as String[] you'll probably get an error even if you do vice versa.

The prototype of this method is



<T> T[] toArray(T[] array)

Note that if the type of the ArrayList is a String and you are passing and taking Integer[] to and from the method respectively, you'll not get a compile time error rather you'll get an exception stating



Exception in thread "main" java.lang.ArrayStoreException
        at java.lang.System.arraycopy(Native Method)
        at java.util.ArrayList.toArray(Unknown Source)

Here is an example illustrating toArray() method. The prototype is
Object[] toArray()



import java.util.*;
class ArrayListToArray
{
    public static void main(String args[])
    {
    ArrayList<String> a=new ArrayList<String>();

    a.add("Gowtham");
    a.add("Gutha's");
    a.add("Java");
    a.add("-");
    a.add("demos");
    a.add(".");
    a.add("blogspot");
    a.add(".");
    a.add("com");

    Object[] ob=a.toArray();
   
    System.out.println("The elements are");

        for(Object k:st)
        System.out.println(k);
    }
}


You'll get the same output for this. But when it comes to explanation, the toArray() method is a non-generic version. The return type of this method is Object[]. However, you can work out with the generic version of the ArrayList class. In this case, it is not even necessary to have ArrayList<String>, it is enough if you write ArrayList. But when you convert to array, you'll not get the generic type however. One more thing is that you cannot typecast it. This is because arrays cannot be typecasted directly like

String[] st=(String[])a.toArray();

which will lead to an error. As you will get an Object[] you cannot access String (here) methods such as substring() etc. Note that by the above statement, you'll not get a compile time error rather you'll receive a ClassCastException.

In this way, conversion of ArrayList into an array made simple. Also see Sort an Array in increasing order

Spring Framework Subtract Elements in Array in Java

An example code on subtracting elements in array in Java in decreasing order in 3 main steps. This simple logic can also be used on any programming language.


Subtract Elements




import java.util.*;

class SubArray

{

public static void main(String args[])

{





// Create Scanner object for taking input from cmd

Scanner s=new Scanner(System.in);





// Read no.of elements for array and store it in n

int n=s.nextInt();





// Create array of n elements

int[] a=new int[n];





// Loop n times

for(int i=0;i<a.length;i++)

{



// Take input from user and store in each element

a[i]=s.nextInt();



}





// Modify the array, arrange it in increasing order

Arrays.sort(a);





// Initialize sub value to 0

int sub=0;





// Loop from end to start (decreasing order)

for(int i=a.length-1;i>=0;i--)

{





// Subtract old value from new value

sub=sub-a[i];



// For the first time, the value is -ve so make it +ve

if(i==(a.length-1))

// To do that, multiply with -1

sub=-1*sub;



// Print every element in array in decreasing order

System.out.println("array "+a[i]);





}





// Print the result

System.out.println("Difference of all elements in array in decreasing order "+sub);





}





}


Sample Output




5


5


4


3


8


1


array 8


array 5


array 4


array 3


array 1


Difference of all elements in array in decreasing order -5


Analysis


Loop from end to start: So that i could arrange those elements in decreasing order as the Arrays.sort() was called previously, all the elements in the array are arranged in increasing order.

n=5, sub=0, a[0]=5, a[1]=4, a[2]=3, a[3]=8, a[4]=1 (before sorting). In increasing order, a[0]=1, a[1]=3, a[2]=4, a[3]=5, a[4]=8 (after Arrays.sort(a))

sub=sub-a[i]:

In decreasing order, i is initially equal to 4, so

0=0-8 = -8 => sub=-8

i==a.length-1 => i==4? true -> sub= -1*sub => -8=-1*-8 = 8 => sub=8

8=8-5=3 => sub=3

3=3-4=-1 => sub=-1

-1=-1-3=-4 => sub=-4

-4=-4-1=-5 => sub=-5

-5 will be printed. The if condition is satisfied for the first time only. Still more efficient logic is appreciated in the comments.
Also see my other posts on Adding elements in array in Java and sorting array elements in increasing order in Java

Spring Framework Sort Array in Increasing Order in Java

An example code on sorting an array of (any numeric datatype) in increasing order in a single statement.

Sorting Array in Increasing Order




import java.util.*;

class SortIntArray

{





public static void main(String args[])

{





// Create Scanner object

Scanner s=new Scanner(System.in);





// Take no.of elements in array

int n=s.nextInt();





// Create an array of n elements

int[] a=new int[n];





// Loop till end of array

for(int i=0;i<n;i++)

{





// Read int from user and store

a[i]=s.nextInt();





}





Arrays.sort(a);



// Say user that is sorted array

System.out.println("Sorted array");





// 'i' represents every element in array 'a'

for(int i:a)

{

System.out.println(i);

}





}





}


Output




5


3


5


6


8


7


Sorted array


3


5


6


7


8




There in fact no analysis that can be done, the logic is written by the developers of the class java.util.Array therefore removing the burden for the app developers to do this. That's why Java developers love to code in Java! Happy java coding :)

Spring Framework StringTokenizer in Java Example

An example on using java.util.StringTokenizer for counting no.of tokens split by a delimeter, using the methods hasMoreTokens(), nextToken() etc..


StringTokenizer Example




import java.util.*;

class StringTokenizerDemo

{





public static void main(String args[])

{





String st1="this is a test";

String st2="this,is,a,test";

String st3="this.is.a.test";





// Create a StringTokenizer with default delimeter i.e. space

StringTokenizer s1=new StringTokenizer(st1);





// Create a StringTokenizer with ',' as delimeter

StringTokenizer s2=new StringTokenizer(st2,",");





// Create a StringTokenizer with default delimeter i.e. space

StringTokenizer s3=new StringTokenizer(st3);





// Print the no.of tokens split by delimeter above

System.out.println("No.of tokens for s1 are "+s1.countTokens());

System.out.println("No.of tokens for s2 are "+s2.countTokens());

System.out.println("No.of tokens for s3 are "+s3.countTokens());





// Loop till hasMoreElements return false

while(s1.hasMoreElements())

{

System.out.println(s1.nextToken());

}





System.out.println();





// Loop till hasMoreTokens return false

while(s2.hasMoreTokens())

{

System.out.println(s2.nextElement());

}





System.out.println();





// Loop till hasMoreElements return false

while(s3.hasMoreTokens())

{

System.out.println(s3.nextToken("."));

}



}





}


Explanation


s1=new StringTokenizer(st1): Create StringTokenizer for the first string st1. The default delimeter is a blank space. A delimeter is nothing but a string that is used for separating another string.

s2=new StringTokenizer(s2,","): Here, we have specified ',' as the delimeter. So this is used to split the string s2 into parts called tokens separated by a comma. This acts as s2.split(",").

s3=new StringTokenizer(st3): Create StringTokenizer with default delimeter pointing st3.

s1.nextToken(): Get's the next token in the string nothing but the word that is after the delimeter (here word after the space). You'll have to note that this also includes the first token though it doesn't have the specified delimeter (space) before it i.e. the first word this

s2.nextElement(): Same as the above, but not the set of characters between a space, but the set of characters between a comma also including the first one.

s3.nextToken("."): This returns the token enclosed between two dots (.) also including the first word (this) but not space. Though the delimeter was not specified in the constructor, it was specified here (i.e. in the nextToken(".") method) to get the tokens enclosed between dots.

Note: The s3.countTokens() method returns only one i.e. only the first token is returned as the default delimeter was space and there was no space found in the string st3 so the first one (from starting till ending) was returned.

Output


No.of tokens for s1 are 4

No.of tokens for s2 are 4

No.of tokens for s3 are 1

this

is

a

test



this

is

a

test



this

is

a

test

Spring Hibernate Java Random Number Generator

Java Random Number Generator

Here is a sample tutorial for generating random numbers in Java using java.util.Random class.

Random int number Java - Range Unspecified


import java.util.Random;
class JavaRandomNumber
{
public static void main(String args[])
{
// Create Random object
Random r=new Random();

// Generate 10 random integers

for(int i=0;i<10;i++)
{
int randomint=r.nextInt();
System.out.println("Random Integer : "+randomint);
}
}
}

r.nextInt(): Returns random number.

Random Java int number Generator - Range Specified


import java.util.Random;
class JavaRandomNumberRange
{
public static void main(String args[])
{
// Create Random object
Random r=new Random();
// Generate 10 random integers between 0 - 100

for(int i=0;i<10;i++)
{
int randomint=r.nextInt(100);
System.out.println("Random Integer : "+randomint);
}
}
}

r.nextInt(100): Returns random number from 0 - 100.


Random Java Long Number Generator



import java.util.Random;
class JavaRandomNumberLong
{
public static void main(String args[])
{
// Create Random object
Random r=new Random();
// Generate 10 random long values

for(int i=0;i<10;i++)
{
long randomlong=r.nextLong();
System.out.println("Random Integer : "+randomlong);
}
}
}


r.nextLong(): Generate random long number.


Java Random Boolean Value Generator


import java.util.Random;
class JavaRandomBoolean
{
public static void main(String args[])
{
// Create Random object
Random r=new Random();
// Generate random boolean - 10 times

for(int i=0;i<10;i++)
{
boolean randomboolean=r.nextBoolean();
System.out.println("Random Boolean : "+randomboolean);
}
}
}

r.nextBoolean(): Generates random boolean value (true/false).


Java Random Float Number Generator


import java.util.Random;
class JavaRandomFloat
{
public static void main(String args[])
{
// Create Random object
Random r=new Random();
// Generate random float - 10 times

for(int i=0;i<10;i++)
{
float randomfloat=r.nextFloat();
System.out.println("Random Float : "+randomfloat);
}
}
}

r.nextFloat(): Generates random float value.


Java Random Double Number Generator


import java.util.Random;
class JavaRandomDouble
{
public static void main(String args[])
{
// Create Random object
Random r=new Random();
// Generate random double - 10 times

for(int i=0;i<10;i++)
{
double randomdouble=r.nextDouble();
System.out.println("Random Double : "+randomdouble);
}
}
}


r.nextDouble(): Generates random double value.


Java Random Byte Numbers


import java.util.Random;
class JavaRandomBytes
{
public static void main(String args[])
{
// Create Random object
Random r=new Random();
// Generate 10 random byte values, store in byte array
byte[] b=new byte[10];

r.nextBytes(b);

for(byte t:b)
{
System.out.println(t);
}

}
}


r.nextBytes(b): Generates 'b' array length sized byte values & store them in b.

Note: Outputs vary.

Spring Framework Printing a Right Triangle in Java

Printing the Right Triangle in Java
Let us print a right angled triangle on the console in Java. Doing this is very simple if you put a very little effort. The following code sample illustrates how this can be achieved.







import java.util.*;

class RightTriangle

{

    public static void main(String args[])

    {



    Scanner s=new Scanner(System.in);



    System.out.println("Enter the base length (chars)");

    int n=s.nextInt();



    System.out.println("Enter the char");

    char st=s.next().charAt(0);

   

        for(int i=0;i<=n;i++)

        {

            for(int j=0;j<i+1;j++)

            {

            System.out.print(st);

            }

        System.out.println();

        }   

    }

}

Sample Output



Enter the base length (chars)

10

Enter the char

`

`

``

```

````

`````

``````

```````

````````

`````````


Explanation

n is an integer which represents the base length i.e. the no.of chars in the last line.
st represents the char that is to be used to draw the right angled triangle.
The two loops together draw the right angled triangle. Let us first consider the inner loop.
The inner loop is dedicated to print the required no.of given chars. It is obvious that the loop condition fails, whenever j becomes i+1.
The outer loop, rotates from 0 till the value of n (base length).
The inner loop rotate from 0 to i+1. Let us analyze the program for better understand.

For the first time


i=0;

j=0; j<0+1? (true) -> Print a `

j++; (j=1)

1<1? (false) -> Exit inner loop -> System.out.println();

i++; (i=1);

For the second time



i=1;


j=0; j<1+1? (true) -> Print a `


j++; (j=1); 1<1+1? (true) -> Print a `


j++; (j=2);


2<2? (false); -> Exit inner loop -> System.out.println();

This continues so on, it depends upon the value of n. Whatever, a right angled triangle is printed and this how we can achieve this in Java.

Labels

.equals = operator abstract class abstract method abstract window toolkit Access Modifiers accessing java beans accessing javabeans action events actionperformed active addition Advanced Advanced Overloading AdvJavaBooks Agile development ajax alive AMQP and Android anonymous class anonymous inner class Ant ant tutorials anti patterns antipatterns Apache Camel api for jsp api for servlet api for servlets api jsp application context application scope application session Apps Architecture are you eligible for the ocmjd certificaiton are you eligible for the scjd certification arithmetic operator arpanet array construction array declaration array initialization array list array to list conversion arraylist arraylist of strings arraylist of types arraylist questions arraylists Arrays arrays in java ask for help assert assert in java assertions assertions in java assignment assignment operator Atlassian attribute visibility authentication authorization autoboxing autounboxing awt AWT Event Handling awt interview questions AWT Layouts awt questions awt questions and answers backed collection backed collections Basic Basics of event handling bean attributes bean properties bean scope Beginner best practices BigData blocked books boxing buffer size bufferedreader bufferedwriter business delegate business delegate pattern calendar case statement casting in java casting interview questions chapter review choosing a java locking mechanism choosing a locking mechanism choosing a thread locking mechanism class inside a method class questions class with no name class without a name classes interview questions Clipboard closing jsp tags code snap coding cohesion collection generics collection interview questions collection methods collection of types collection questions collection searching collection types Collections Collections Framework collections interview questions collections sorting colors in java swings colors in swing command line arguments communication between threads comparable comparator comparison operators compiling java classes computers concurrency example and tutorial config Configuration ConnectionPooling constructor creation constructor interview questions constructor overloading constructors in java containers contents of deployment descriptor contents of web.xml context context scope converting array to list converting list to array core java core java interview core java interview question core java interview questions core java questions core java; core java; object oriented programming CoreJava CoreJavaBooks CORS coupling create threads creating 2 dimensional shapes creating 2D shapes creating a frame creating a jframe creating a thread creating an arraylist creating an inner class creating an interface creating java beans creating java threads creating javabeans creating threads creating threads in java CSS cURL currency current thread determination custom tag library custom taglib custom taglibs custom tags CVS dao dao design pattern dao factory pattern dao pattern data access object data access object pattern data structure and algorithm database date and time tutorial date format dateformat dates deadlock deadlocks debugging Declarations decorator pattern decrement default deleting sessions deploy web app deployment deployment descriptor deployment descriptor contents deployment of web application deserialization deserialize design pattern design pattern interview questions design patterns Designpatterns destory method destroy destroying sessions determining current thread determining the current thread Developer Differences different types of collections display stuff in a frame displaying images displaying images in java swings displaying images in swings displaying text in a component division do while loop doget dohead dopost doput DOS Downloads drawing a line drawing an ellipse drawing circles drawing ellipses drawing lines Drools tutorial eBooks Eclipse Eclipse Tutorial Encapsulation encapsulation in java enhanced for loop entity facade pattern enumerations enumerations in java enums equal to equals equals comparison error and exception error codes error handling in servlets error page event handling in swings event listeners exam prep tips example servlet Examples exception exception handling exception handling in servlets exception handling interview questions exception handling questions Exceptions exceptions in java exceptions in web applications explicit locking explicit locking of objects file file navigation filereader filewriter final class final method FireBug first servlet FIX protocol FIX Protocol interview questions FIX protocol tutorial font fonts for each loop for loop form parameters form values formatting forwarding requests frame frame creation frame positioning frame swings front controller front controller design pattern front controller pattern fundamental.Java FXML Games garbage collection garbage collection interview questions garbage collection questions garbage collector gc gc questions general generic Generics generics collections Geo get get set methods getattribute getting bean property getting form values getting form values in servlet getting scwcd certified getting servlet initialization parameters getting sun certified Google Graphics2D gregorian calendar handling strings in java hash hash map hash table hashcode hashmap hashset hashtable head head request HeadFirst heap heaps hibernate hibernate interview questions hibernate interview questions and answers hibernate questions hibernate questions and answers Hibernate Tutorial HibernateBooks homework How To HTML HTML and JavaScript html form http request http request handling http request header http request methods http request servlet http request type http session httprequest httprequest methods httpservlet httpservlet interview questions httpservlet interview questions with answers httpsession httpsession interview questions httpsession questions HttpSessionActivationListener HttpSessionAttributeListener HttpSessionBindingListener if if else if else block if else statement Image IO implementing an interface Implicit objects increment info inheritance inheritance in java init init method Initialization Blocks inner class inner class inside a method inner classes innerclass installation instanceof instanceof operator IntelliJ interaction between threads interface interface interview interface questions interfaces interfaces in java interfaces interview questions internet history interrupting a thread interrupting threads Interview interview questions interview questions on design patterns interview questions on exception handling interview questions on java collections interview questions on serialization introduction to java threads introduction to jsps introduction to threading introduction to threads invalidating session Investment Banking IO Package iscurrentthread iterator J2EE j2ee api j2ee design pattern j2ee design pattern interview questions j2ee design patterns j2ee hibernate interview questions j2ee history j2ee interview j2ee interview questions j2ee mvc j2ee mvc pattern j2ee programmer j2ee questions j2ee servlet api j2ee session j2ee struts interview questions java java 5 tutorial Java 8 java arrays java assertions java assignments java awt questions java bean java bean scope java beans java beginners tutorial Java career java certification Java Class java collection interview questions and answers java collection tutorial java collections java collections interview questions java constructors java currency Java CV java data base connectivity java database connectivity java database connectivity interview questions and answers java dates java design pattern java design patterns java developer certification Java EE java encapsulation java enums java event listeners java exceptions java formatting java garbage collection java garbage collector java gc java heap Java I/O java inheritance java input output Java Interface Java Interview Java Interview Answers Java Interview Questions Java Introduction java io java IO tutorial java iterator java jdbc Java JSON tutorial Java Key Areas java lists java literals java locks nested Java Media Framework java methods java multithreading Java multithreading Tutorials java nested locks java networking tutorial java numbers Java Objects java operators java overloading java parsing Java Programming Tutorials java race conditions java regex java regular expressions Java resume java scjp java searching java serialization java server pages java server pages api java server pages questions java spring interview questions. j2ee spring interview questions java stack java strings java swing java swing event listeners java swing frame java swing images java swings java swings images java thread explicit locking java thread lock scope java thread locking java thread locking mechanism java thread locking objects java threads java threads race condition java tips java tokenizing Java Tools Java Tutorial java ui questions Java Utilities java variables java wrappers Java xml tutorial java.lang java8 javabean javabean accessing javabean scope JavaBeans javac JavaEE JavaFX JavaFX 3D JavaFX 8 JavaOne JavaScript JavaTips JDBC jdbc driver jdbc example jdbc interview questions jdbc interview questions and answers jdbc interview questions with answers jdbc sample code JDBC Tutorial jdbc type 1 driver jdbc type 2 driver jdbc type 3 driver jdbc type 4 driver Jdeveloper JDK JDK8 JEE Tutorial jframe jframe creation jframe position jframe positioning JIRA JMeter JMS JMX join() joining threads JPA JQuery JS JSF JSF Tutorial JSONP JSP jsp and java beans jsp and servlets jsp and xml jsp api jsp code jsp compilation jsp conversion jsp directives jsp error page jsp error page directive jsp implicit objects jsp interview jsp interview questions jsp introduction jsp intvw questions jsp life jsp life cycle jsp life-cycle jsp lifecycle jsp page directive jsp questions jsp sample jsp scripting jsp scriptlets jsp servlets jsp summary jsp synopsis jsp tag libraries jsp tag library jsp taglib jsp tags jsp technology jsp to servlet jsp to servlet conversion jsp translation jsp usage jsp usebean jsp xml tags jsp xml tags usage jsp-servlet jsp:getProperty jsp:setProperty jsp:usebean jsps JSTL JUnit testing keyword synchronized keyword volatile Keywords Lambda Expressions Learning libraries life cycle life cycle of a jsp life cycle of a servlet life cycle of a thread life cycle of jsp life cycle of threads lifecycle of a thread linked list linkedhashmap linkedhashset linkedlist linux List listeners lists Literals locale lock manager pattern lock scope locking objects using threads log Logging logging errors logical and logical operators logical or loops loosely coupled making an arraylist making threads sleep making threads sleep for time MapReduce maps maps usage Maven Maven Tutorial max priority member access method arguments method local inner class method overloading method overriding method return types methods creating classes min priority Miscellaneous mobile mock exam model view controller model view controller design pattern model view controller pattern Multi Threading Multi-threading multiple threads multiplication multithreading multithreading in java multithreading interview questions multithreading questions mvc mvc design pattern mvc pattern MyEclipse mysql nested java lock nested java locks nested java thread locks nested locks nested thread locks NetBeans Networking new news nio NonAccess Modifiers norm priority normal inner class Normalization not equal to Notepad notify notifyall number format numberformat numbers object comparison object notify object orientation object oriented object oriented programming Object Oriented Programming in java objects interview questions ocmjd certification ocmjd certification eligibility OO OO Java oops OpenCSV OpenCV opening jsp tags OpenJDK OpenJFX Operators or Oracle Oracle ADF Mobile Oracle Certified Exams oracle certified master java developer oracle database ORM other topics out overloading overloading constructors overloading in java overriding page page directive page scope parsing passing variables passing variables to methods performance Platform Playing with Numbers points to remember polymorphism positioning a frame post practice exam Primitive Casting primitive variables printwriter priority queue priority queues priorityqueue priorityqueues private processing form values Products programming Projects protected public put questions questions on garbage collection questions on java strings queue quick recap quick review race conditions read objects from stream reading http request header RealTime_Tips redirecting to another servlet redirection reference reference variable casting reference variables Refreshing Java regex Regular Expressions regular inner class relational operators reminder request request dispatcher request forwarding request header request object. httpservletrequest request scope requestdispatcher response RESTClient RESTful retrieving values from session return error codes return types returning values runnable runnable interface running running java programs RUP sample jsp sample questions sample questions scwcd sample servlet scanner Scene Builder scjd certification scjd certification eligibility requirements scjp SCJP Certification scjp exam scjp exam questions scjp exam sample questions scjp questions scjp test scjp test questions scope scope of java locks scope of java thread locks scope of locks scripting in jsp scriptlet tags scriptlets scriptlets in jsp pages scwcd scwcd certification scwcd certification practice exam scwcd exam scwcd exam questions scwcd jsp summary scwcd mock exam scwcd mock exam answers scwcd practice exam scwcd practice test scwcd questions scwcd test SDLC searching searching arrays searching collections searching in java searching treemap searching treesets security self assement self assement scwcd self assessment scjp self test self test scjp self test scwcd send error method senderror method sending error code to browser serialization serialization in java serialization interview questions Serialization on Swing serialization questions service service method servlet servlet and forms servlet and jsp servlet api servlet attributes servlet code servlet container servlet context servlet error handling servlet exception handling servlet handling http request servlet initialization servlet initialization parameters servlet interview servlet interview questions servlet interview questions with answers servlet intvw questions servlet life cycle servlet lifecycle servlet questions servlet questions with answers servlet request servlet request dispatcher servlet request type servlet skeleton servletcontext servletcontextevent servletrequest Servlets servlets and jsps servlets api servlets details servlets request handling session session clean up session event listeners session facade pattern session interview questions session invalidation session listeners session management session questions session scope session timeout session tracking through url rewriting set collections set status method setattribute sets setstatus method setting bean property setting request type short circuit operators Singleton sleep sleeping threads soapUI Software Installation sorting sorting arraylist sorting arrays sorting collections special collections special inner classes split spring spring and hibernate interview questions spring batch Spring Core Spring Framework Spring Integration spring interview questions Spring JDBC Spring MVC Spring security Spring tutorial SQL SQL and database tutorial examples SQL Tutorial SSL stack stacks stacks and heaps static static class static declaration static imports static inner static inner class static method Static variable stopped stopping a thread stopping thread stopping threads Stored Procedure storing values in session Streams strictfp StrictMath string string buffer string builder string class string formatting String Handling string interview questions string manupulation string questions string tokenizer stringbuffer stringbuffer questions stringbuilder Strings strings in java struts Struts 1 Struts 1.2 Struts 2 struts framework interview questions struts interview questions struts interview questions with answers struts mvc interview questions struts questions Struts2 StrutsBooks submitting request subtraction Sun Certification sun certified java developer Sun Certified Java Programmer swing swing action performed swing and colors Swing Components swing event handling swing event listeners swing events Swing Hacks swing images Swing Look And Feels swings swings frame switch block switch case block switch case statement Sybase Sybase and SQL Server synchronization synchronized code synchronized keyword synchronized method System Properties tag lib tag library tag-lib taglibs tags TDD Technical Blogging ternary operator Test Driven Development test scjp Testing the context the session the volatile keyword thread thread class thread deadlocks thread interaction thread interruption thread life cycle thread lifecycle thread lock scope thread locks thread notify thread priorities thread race conditions race conditions in threads thread sleep thread states thread stoppage thread stopping thread synchronization thread syncing thread yield Threads threads in java threads interview questions threads life cycle threads questions tibco tightly coupled tips tips and tricks tips.FXML tokenizing Tomcat Tools toString transitions treemap treeset tricks Tricks Bag try catch try catch finally. finally block Tutorial type casting in java ui programming with java swings UML unboxing unit testing unix url rewriting use bean usebean using a arraylist using collections using colors using colours using command line arguments using different fonts using expressions using font using fonts using fonts in swings using hashmap using http session using httpsession using iterator using java beans in jsp using javabean in jsp using javabeans in jsp using javac using lists using maps using request dispatcher using scriptlets using session persistense using sets using special fonts using system properties using the jsp use bean using treeset using use bean Using Variables using volatile Using Wrappers using xml in jsp Util pack value object value object design pattern value object pattern var-args varargs Variable Arguments Variables vector vector questions vectors visibility vo pattern volatile volatile keyword volatile variables wait method waiting web app exception handling web app interview web application deployment web application exceptions web application scope web application security web component developer web component developer certification web context web context interfaces web context listeners web interview questions web security web server web servers Web services web.xml web.xml deployment webapp log weblogic website hacking website security what are threads what is a java thread what is a thread what is thread while loop windows windows 8 wrapper classes wrappers write objects to stream WSAD xml xml and jsp xml tags xslt yield()