DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
  • submit to reddit

Java Snippets

  • java code
  • String
  • alpha-numeric
                    private static final String ALPHA_NUMERIC_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
public static String randomAlphaNumeric(int count) {
		StringBuilder builder = new StringBuilder();
		while (count-- != 0) {
			int character = (int)(Math.random()*ALPHA_NUMERIC_STRING.length());
			builder.append(ALPHA_NUMERIC_STRING.charAt(character));
		}
		return builder.toString();
}                
  • java
  • graphics
  • 2D and 3D Animation
  • AWT
                    package com.dyrio.graphics;

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class Graphics1 extends Frame {

	private static final long serialVersionUID = 1L;
	private int xPosition = 100;
	private int yPosition = 50;
	private static final int xSize = 300;
	private static final int ySize = 100;
	private static Graphics2D graphics2D;
	private static final String MESSAGE = "Welcome to 2D Graphics";
	
	public Graphics1() {
		addWindowListener(new ExitAdapter());
	}
	
	public void paint(Graphics g) {
		graphics2D = (Graphics2D) g;
		graphics2D.drawString(MESSAGE, xPosition, yPosition);
	}
	
	public static void main(String[] args) {
		Graphics1 graphics1 = new Graphics1();
		graphics1.setTitle("Graphics 1");
		graphics1.setSize(xSize,ySize);
		graphics1.setVisible(true);
	}
	
	public class ExitAdapter extends WindowAdapter
	{
		public void windowClosing(WindowEvent e)
	     {
	       System.exit(0);
	     }
	}
}
                
  • Greasemonkey
  • firefox
  • javascript
                    <code>// ==UserScript==
// @name          get rid of amg crap
// @namespace     polestar
// @include       *allmusic.com*

// ==/UserScript==

(function()
{
    inner = 'AMG blocker';
    amgCrap = document.getElementById( 'adverttop' );
    amgCrap.innerHTML = inner;
    amgCrap = document.getElementById( 'header' );
    amgCrap.innerHTML = inner;
    amgCrap = document.getElementById( 'right' );
    amgCrap.innerHTML = inner;
    amgCrap = document.getElementById( 'NR' );
    amgCrap.innerHTML = inner;
    amgCrap = document.getElementById( 'right-sidebar' );
    amgCrap.innerHTML = inner;
})();
</code>                
  • hello
  • javascript
                    <code>
<script language='javascript'>
alert('hello world')
</script>
</code>                
  • java
  • ShortCircuit
  • operator
                    <code>
(++i < i-- && j++ > j--)
</code>

Doesnot evaluate the second operand of the && opeartor.

                
  • java
  • processing
                    <code>
  
  void intersect()
  {
     float m1,m2,b1,b2,ix,iy;
     Position p1a = new Position(mouseX, mouseY);
     Position p1b = new Position(points[maximum-1]);
     Position p2a = new Position();
     Position p2b = new Position();

     strokeWeight(4);
     stroke(0,255,0);
     line(p1a.x, p1a.y, p1b.x, p1b.y);
     
     // comparison line segment
     m1 = (p1a.y - p1b.y) / (p1a.x - p1b.x);
     b1 = p1a.y-m1*p1a.x;
     
     // cycle through each line segment on the gesture backwards
     for (int i = maximum-1; i > 0; i--) {
       
       //if (points[i].x < 0 && points[i].y < 0) { continue; }
       
       p2a.set(points[i]);
       p2b.set(points[i-1]);
       
       // second line segment
       m2 = (p2a.y - p2b.y) / (p2a.x - p2b.x);
       b2 = p2a.y - m2*p2a.x;
       
       if (m1 != m2) { // if they're not parallel
       
         // find the intersection
         ix = (b2-b1)/(m1-m2);
         iy = m1*ix+b1;
         
         // is the intersection on the line segments?
         if (ix > min(p1a.x, p1b.x) && ix < max(p1a.x, p1b.x) &&
             iy > min(p1a.y, p1b.y) && iy < max(p1a.y, p1b.y) &&
             ix > min(p2a.x, p2b.x) && ix < max(p2a.x, p2b.x) &&
             iy > min(p2a.y, p2b.y) && iy < max(p2a.y, p2b.y)) {
             
             if (i_count < i_max) {
               intersects[i_count].set(ix, iy);
               i_count++;
             } else {
               for (int j = 0; j < i_max-1; j++) {
                 intersects[j].set(intersects[j+1]);
               }
               intersects[i_max-1].set(ix, iy);
             }
             
             println("something");
             // send the points to the shape object
             s.set(points, i);
             reset();
             break;   
         }
       }
     }
</code>                
  • sudoku
  • puzzle
  • java
                    
<code>
import java.util.ArrayList;

public class Sudoku {
	int[][] board = new int [9][9];
	ArrayList[][] workBoard = new ArrayList[9][9];
	
	public void initializeBoard(){
		/***Board:
			[0][0][0][2][6][0][7][0][1]
			[6][8][0][0][7][0][0][9][0]
			[1][9][0][0][0][4][5][0][0]
			[8][2][0][1][0][0][0][4][0]
			[0][0][4][6][0][2][9][0][0]
			[0][5][0][0][0][3][0][2][8]
			[0][0][9][3][0][0][0][7][4]
			[0][4][0][0][5][0][0][3][6]
			[7][0][3][0][1][8][0][0][0]
		***/
		board[0][0] = 0;
		board[0][1] = 0;
		board[0][2] = 0;
		board[0][3] = 2;
		board[0][4] = 6;
		board[0][5] = 0;
		board[0][6] = 7;
		board[0][7] = 0;
		board[0][8] = 1;
		
		board[1][0] = 6;
		board[1][1] = 8;
		board[1][2] = 0;
		board[1][3] = 0;
		board[1][4] = 7;
		board[1][5] = 0;
		board[1][6] = 0;
		board[1][7] = 9;
		board[1][8] = 0;
		
		board[2][0] = 1;
		board[2][1] = 9;
		board[2][2] = 0;
		board[2][3] = 0;
		board[2][4] = 0;
		board[2][5] = 4;
		board[2][6] = 5;
		board[2][7] = 0;
		board[2][8] = 0;
		
		board[3][0] = 8;
		board[3][1] = 2;
		board[3][2] = 0;
		board[3][3] = 1;
		board[3][4] = 0;
		board[3][5] = 0;
		board[3][6] = 0;
		board[3][7] = 4;
		board[3][8] = 0;
		
		board[4][0] = 0;
		board[4][1] = 0;
		board[4][2] = 4;
		board[4][3] = 6;
		board[4][4] = 0;
		board[4][5] = 2;
		board[4][6] = 9;
		board[4][7] = 0;
		board[4][8] = 0;
		
		board[5][0] = 0;
		board[5][1] = 5;
		board[5][2] = 0;
		board[5][3] = 0;
		board[5][4] = 0;
		board[5][5] = 3;
		board[5][6] = 0;
		board[5][7] = 2;
		board[5][8] = 8;
		
		board[6][0] = 0;
		board[6][1] = 0;
		board[6][2] = 9;
		board[6][3] = 3;
		board[6][4] = 0;
		board[6][5] = 0;
		board[6][6] = 0;
		board[6][7] = 7;
		board[6][8] = 4;
		
		board[7][0] = 0;
		board[7][1] = 4;
		board[7][2] = 0;
		board[7][3] = 0;
		board[7][4] = 5;
		board[7][5] = 0;
		board[7][6] = 0;
		board[7][7] = 3;
		board[7][8] = 6;
		
		board[8][0] = 7;
		board[8][1] = 0;
		board[8][2] = 3;
		board[8][3] = 0;
		board[8][4] = 1;
		board[8][5] = 8;
		board[8][6] = 0;
		board[8][7] = 0;
		board[8][8] = 0;
	}
	
	
	public void printBoard(){
		System.out.println("Board:");
		for (int i=0;i<9;i++){
			for (int j=0; j<9; j++){
				//System.out.print("["+i+","+j+"]");
				System.out.print("["+board[i][j]+"]");
			}
			System.out.println("");
		}
	}
	
	public void initializeWorkBoard(){
		for (int i=0;i<9;i++){
			for (int j=0; j<9; j++){
				ArrayList<Integer> cell = new ArrayList<Integer>();
				for (int k=1; k<=9; k++){
					cell.add(k);
				}
				workBoard[i][j] = cell;
			}
		}
	}
	
	public void printWorkBoard(){
		System.out.println("Current Work Board:");
		for (int i=0;i<9;i++){
			for (int j=0; j<9; j++){
				//System.out.print("["+i+","+j+"]");
				System.out.print(""+workBoard[i][j]+" ");
			}
			System.out.println("");
		}
	}
	
	public void removeByColumn(){
		for (int i=0;i<9;i++){ //row
			for (int j=0; j<9; j++){ //column
				ArrayList<Integer> currCell = workBoard[i][j];
				for (int k=0; k<9; k++){ //go down column
					if (currCell.contains(board[k][j]) && i!=k){
						currCell.remove(new Integer(board[k][j]));
					}
					if (workBoard[k][j].size() == 1 && currCell.contains(workBoard[k][j].get(0))&& i!=k){
						currCell.remove(workBoard[k][j].get(0));
					}
				}
			}
		}
	}
	
	public void removeByRow(){
		for (int i=0;i<9;i++){ //row
			for (int j=0; j<9; j++){ //column
				ArrayList<Integer> currCell = workBoard[i][j];
				for (int k=0; k<9; k++){ //go down row
					if (currCell.contains(board[i][k]) && j!=k){
						currCell.remove(new Integer(board[i][k]));
					}
					if (workBoard[i][k].size() == 1 && currCell.contains(workBoard[i][k].get(0))&& j!=k){
						currCell.remove(workBoard[i][k].get(0));
					}
				}
			}
		}
	}
	
	public void fillGivenValues(){
		for (int i=0;i<9;i++){
			for (int j=0; j<9; j++){
				ArrayList<Integer> currCell = workBoard[i][j];
				if (board[i][j] != 0){
					currCell.clear();
					currCell.add(new Integer(board[i][j]));
				}
			}
		}
	}
	
	public void removeBySquare(){
		ArrayList<Integer> numsInSquare;
		for (int i=0; i<9; i+=3){
			for (int j=0; j<9; j+=3){
				numsInSquare  = new ArrayList<Integer>();
				//throw all values in list
				for (int k=0+i; k<3+i; k++){
					for (int l=0+j; l<3+j; l++){
						numsInSquare.add(new Integer(board[k][l]));
						if (workBoard[k][l].size() == 1){
							numsInSquare.add((Integer) workBoard[k][l].get(0));
						}
					}
				}
				for (int k=0+i; k<3+i; k++){
					for (int l=0+j; l<3+j; l++){
						ArrayList<Integer> currCell = workBoard[k][l];
						for (int p=0; p<numsInSquare.size(); p++){
							if (currCell.contains(numsInSquare.get(p)) && currCell.size() > 1){
								currCell.remove(numsInSquare.get(p));
							}
						}
					}
				}
				
			}
		}
	}
	
	public static void main(String args[]){
		Sudoku s = new Sudoku();
		s.initializeBoard();
		s.printBoard();
		
		s.initializeWorkBoard();
		
		for (int i=0; i<10; i++){
			System.out.println("Run "+(i+1));
			s.removeByColumn();
			s.removeByRow();
			s.fillGivenValues();
			s.removeBySquare();
			s.printWorkBoard();
		}
	}
}
</code>                
  • magic square
  • odd
  • java
                    A simple Java program to do this, can be easily rewritten in any language:

<code>
/* * Magic Square */
int order = 5;
for (int row = 0; row < order; row++) {
	for (int col = 0; col < order; col++) {
		int rowMatrix = (((order + 1) / 2 + row + col) % order);
		int colMatrix = (((order + 1) / 2 + row + order - col - 1) % order) + 1;
		System.out.print(((rowMatrix * order) + colMatrix) + "\t");
	}
	System.out.println();

}
</code>

Form a Square Matrix writing numbers 1 to nxn in sequence. Here n is the order of the Magic Square, say 5. 

<code>
1        2       3       4       5  
6        7       8       9      10
11      12      13      14      15
16      17      18      19      20
21      22      23      24      25
</code>

We are trying to identify the final Matrix from the above. Form two matrices, one for identifying the row and another to identify the column. 
<code>
4     5     1     2     3           3     2     1     5     4
5     1     2     3     4           4     3     2     1     5
1     2     3     4     5           5     4     3     2     1
2     3     4     5     1           1     5     4     3     2
3     4     5     1     2           2     1     5     4     3
</code>

You will see the middle column of the first Matrix starts with 1 and are in sequence. Columns on either side can be filled by subtracting and adding 1. The second Matrix is a mirror image.

Form the final Matrix by writing the number from initial Matrix in the corresponding row and column. For e.g 4, 3 (Step 2) = 18 (Step 1) 
<code>
18      22       1       10      14
24       3       7       11      20
5        9      13       17      21
6       15      19       23       2
12      16      25        4       8
</code>

The above steps are applicable for any order of the Magic Square! 
                
  • password generator
  • combination
  • permutation
  • java
                    Forms the unique target combinations, recursively, starting from source list that has all the possible positions (chars).

<code>

import java.util.LinkedList;
import java.util.List;

import org.apache.commons.lang.SerializationUtils;

public class Combinations {
	
	private final static String characters = "abcd";
	
	private static int length = characters.length();
	
	public static void main(String[] args) {
		List<Integer> source = new LinkedList<Integer>();
		
		// form the source list that have all the possible positions
		for (int i = 0; i < length; i++) {
			source.add(i);
		}

		// create a target list for forming unique combinations
		List<Integer> target = new LinkedList<Integer>();

		combine(source, target);

	}
	
	public static void combine(List<Integer> source, List<Integer> target) {

		// break the recursion
		if (target.size() == length) {
			for (int i = 0; i < length; i++) {				
				System.out.print(characters.charAt(target.get(i)));				
			}
			System.out.println();
			return;
		}

		for (Integer position : source) {
			//form the target combination by selecting a position from the source
			List<Integer> reducedSource = (List<Integer>)SerializationUtils.clone((LinkedList<Integer>)source);
			reducedSource.remove(position);
			List<Integer> combinedTarget = (List<Integer>)SerializationUtils.clone((LinkedList<Integer>)target);
			combinedTarget.add(position);
			combine(reducedSource, combinedTarget);			
		}
		source.clear();
		target.clear();
	}
}
</code>                
  • math
  • intersection
  • line
  • java
                    // Find X,Y intersection of 2 lines

<code>
public class findLineIntersection {

	public static void main(String args[]){
		//Ay = Bx + C
		//Dy = Ex + F
		double A,B,C,D,E,F;
		
		A=1; B=2; C=3; D=4; E=5; F=6;
		
		double X = findX(A,B,C,D,E,F);
		double Y = findY(A,B,C,X);
		
		System.out.println("("+X+","+Y+")");
	}
	
	public static double findX(double A, double B, double C, double D, double E, double F){
		double neg =-1;
		double Q,R,S;
		if (A<0 ^ D<0){
			//If A or D is negative add the values
			neg = 1;
		}
		//Eliminate Y using multiple
		double multiple = neg*(A/D);
		D = D*multiple;
		E = E*multiple;
		F = F*multiple;
		
		//Q will be 0
		Q = A+D;
		R = B+E;
		S = C+F;
		return (-S)/R;
	}
	public static double findY(double A, double B, double C, double X){
		return ((B*X) + C)/A;
	}
}
</code>