Posts

Showing posts with the label java

Bit Stuffing Code Implementation in Java

Image
This is an implementation of the Bit Stuffing popularly used in data communication, also known as one of the concepts of Framing data bits. To know more please  click here. Sample Output: This is a sample output with data binary data entered as 11001111110. Program Code: import java.util.*; public class BitStuffing { public static void main(String[] args) { System.out.print("Enter the Binary message: "); Scanner sn=new Scanner(System.in); String data = sn.nextLine(); String res = new String(); String out=new String(); int counter = 0; for(int i=0;i<data.length();i++) { if (data.charAt(i)!='1' && data.charAt(i)!='0') { System.out.println("Enter only Binary values!!!"); return; } ...

AWT Program to display the given input on button click

Image
This is a program which will accept the input from the keyboard and on clicking the button, it will show the given input. This program is compiled in Eclipse. This is a basic program in Java using AWT where a single TextField, Label and a Button is used. Screenshot The Code: package dProBuk; import java.awt.Button; import java.awt.Frame; import java.awt.GridLayout; import java.awt.Label; import java.awt.TextField; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class SimpleLayoutAWT implements ActionListener { TextField t; Label l; Button b; public SimpleLayoutAWT() { // TODO Auto-generated constructor stub Frame f=new Frame("Simple Frame"); t=new TextField("Enter the Name"); l=new Label(""); b=new Button("Show !"); f.setLayout(new GridLayout(3,1)); f.setVisible(true); f.setSize(500,200); f.add(t); f.add(b); ...

A simple program to check anagrams in java

Image
This is a simple program in Java. This program can be used to check if the two given strings are anagram. Two given strings are said to be anagrams when they have equal length and same characters are present in both the Strings. An example of anagram strings is SILENT and LISTEN ! Screenshot The Code: import java.util.*; public class Anagram { public static boolean isAnagram(String s1,String s2) { if(s1.length()!=s2.length()) { return false; } s1=sortCharacters(s1); s2=sortCharacters(s2); return s1.equals(s2); } public static String sortCharacters(String str) { char[] c=str.toLowerCase().toCharArray(); Arrays.sort(c); return String.valueOf(c); } public static void main(String arg[]) { String s1,s2; Scanner sc=new Scanner(System.in); System.out.println("enter 2 strings"); s1=sc.nextLine(); s2=sc.nextLine(); if(isAnagram(s1,s2)) System.out.println(s1+"is an anagram"+s2); else System.out.println(s1+"is...

Creating a Calculator panel using AWT in Java

Image
The Real power of java comes into the picture in AWT and Applet in java. We can create a popup window and program it according to our use, just like real life applications in the computers. It is a simple design of a calculator using AWT and Swing. Screenshots: Calculator panel in ubuntu Calculator panel in Windows The Code: import java.util.*; import java.awt.*; import javax.swing.*; class calculator extends Frame { Panel number,text_box,operation,buttons; JFrame cal; /*Creating and object for JFrame*/ /*Creating Buttons and TextBox reference variables*/ Button one,two,three,four,five,six,seven,eight,nine,zero,dot,plus,minus,mul,div,percentage,factorial,log,Ln,brac1,brac2; TextField box; public calculator() { /*Configuring frame of the window and Heading, Layout, close button action*/ cal = new JFrame(); cal.setTitle("CALCULATOR"); /*Title of the window*/ cal.setSize(500,500); /*size of the window in pixels*/ cal.setLayout(new F...

Java Program to separate vowels & consonants in a File.

Image
PROGRAM   DESCRIPTION: This Program creates one file which stores a String. It separates the input String into vowels and consonants and stores them in two different File. Here one extra File is used to store nonalphabate values. Sample Output: CODE: import java.io.*; import java.util.*; class File1 { public static void main(String[] args) throws Exception { Scanner sc=new Scanner(System.in); System.out.println("Enter a String:"); String data1=sc.nextLine(); FileOutputStream fos=new FileOutputStream("abc.txt"); byte[] b1=data1.getBytes(); fos.write(b1); FileInputStream fis=new FileInputStream("abc.txt"); int size=fis.available(); byte[] b2=new byte[size]; fis.read(b2); String data2=new String(b2); FileOutputStream fos1=new FileOutputStream("vowels.txt"); FileOutputStream fos2=new FileOutputStream("consonants.txt"); FileOutputStream fos3=new FileOutputStream("nonalph...

Program to find strings are "anagram" or not

Image
                                 This is a program which uses java concept to find out the given strings are anagram or not. Well, anagram is a concept in which two strings will be having same alphabets but the spelling would be different. This program uses String class to declare objects and the methods used are accordingly to check the strings. Look at the sample output and the code given below. Sample Output: Program Code: import java.util.*; class AnagramEx { public static void main(String[] args)throws Exception { Scanner sc=new Scanner(System.in); System.out.println("Enter first string:"); String s1=sc.nextLine(); System.out.println("Enter second string:"); String s2=sc.nextLine(); Boolean flag=true; int i,j; i=s1.length(); j=s2.length(); if(i==j) { for (int k=0;k<i ;k++ ) { for(int l=0;l<i;l++) { if(s1.charAt(k)==s2.charAt(l)) {...

How multitasking or multi-threading is working in Java

Image
Java supports the multi tasking concept using time sharing concept of CPU. It switch from one task to another task in the midway. We can control the switching time using sleep or wait method. It's a totally random process, we cannot predict the order. Screenshot/Output: Using the try block ( sleep method) Without using the try block ( sleep method) The Code: class Demo1 extends Thread { public void run() { for(int i=0;i<10;i++) { System.out.println("Thread 1 "+i); /*try { Thread.sleep(200); } catch(InterruptedException e) { System.out.println(e); }*/ } } } class Demo2 extends Thread { synchronized public void run() { for(int i=0;i<20;i++) { System.out.println("\t.\t Thread 2 "+i); /*try { Thread.sleep(100); } catch(InterruptedException e) { System.out.println(e); }*/ } } } class Demo3 extends Thread { public void run() { for(int i=0;...

64 Bit Decimal to Binary Converter In Java

Image
Hey, Have you ever think about the simple basic things, the Binary. Yeah , whatever we do in any digital electronics device all are processed and stored in memory in binary. Its a basic. The conversion of decimal to binary.... Yeah, we all know about it. Its just division and reminder.. and repeat.. But how we efficiently do that... And we have limitation.. Of-course we have.. Even computers have.. A 64 bit binary in Decimal is around 10 to the power 19... yeah very large enough... Now we convert Decimal to Binary.. lets check the limitation... Screenshot / Output Showing the bit length and the binary equivalent of the decimal input The Code: import java.util.*; public class binary { public static void main(String arg[]) { System.out.print("Give the decimal Number: "); Scanner s = new Scanner(System.in); long n = s.nextLong(); long a[] = new long[64]; int i,j,k; for(i = 0; i<64; i++) { a[63-i] = (n%2); n=n/2; } fo...

Solve Determinant of N x N Matrix in Java

Image
This is a Java program which can be used to find the Determinant of any Matrix. This program involves transforming the given N x N matrix to a Upper Triangle form. Screenshot[Demo] The Code package dProBuk; import java.util.Scanner; public class Det { public static void main(String[] args) { // TODO Auto-generated method stub Scanner s= new Scanner(System.in); int n; System.out.println("Give the value of N for [N x N]: "); n=s.nextInt(); double a[][]=new double [n][n]; //Storing Values in the Array ! for (int i=0;i<n;i++) for (int j=0;j<n;j++) a[i][j]=s.nextInt(); // Conversion of matrix to upper triangular for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) if(j>i) { double ratio = a[j][i]/a[i][i]; for(int k = 0; k < n; k++) a[j][k] -= ratio * a[i][k]; } } double det = 1.0;...

Binary Search using Java

Image
It is a technique to search an element in sorted array. In this type of search half of the array is ignored just after one comparison. Each time required element is compared with middle element of the array and range is decided . Best Case Performance :  O(1) Average Case Performance : O(log n) Worst Case Performance : O(log n) Demo Output: The Program import java.util.Scanner; public class BinarySearch1 { public static void main(String args[]) { int i, first=0, last, mid, no, element; Scanner s = new Scanner(System.in); System.out.println("\n How many elements:"); no= s.nextInt(); int arr[]= new int[no]; System.out.println("\n Enter the elements:"); for (i = 0; i < no; i++) arr[i] = s.nextInt(); System.out.println("\n Enter the element to be searched:"); element = s.nextInt(); last = no - 1; mid = (first + last)/2; while( first <= last ) { if ...

User Defined Packages In Java

Image
This post will demonstrate the creation of user defined packages and use them. Basically we will use a Math class and an IO class. These two classes will be included in a package sample . Math class will perform all basic add, mul, sub, div operations. On the other side, the IO class will handle with input and output operations. Screenshot[Final Output] The Code Section Firstly creating the Math.java file package sample; public class Math { public int add(int a, int b)   {     return a+b;   }   public int mul(int a, int b)   {     return a*b;   }   public int sub(int a, int b)   {     return a-b;   }   public int div(int a, int b)   {     return a/b;   } } Secondly creating the IO.java file package sample; import java.util.Scanner; public class IO {   Scanner s;   public IO()   {     s= new Scanner(System.in);   } ...

User Defined Exceptions in Java

Image
In this post you will learn to create your own, user defined exceptions. This program will handle unchecked exceptions, i.e those exceptions which cannot be checked by the compiler, or the run time exceptions. In this program there is a simple class AgeMargin in which when the age is less then 18 or greater then 24 generates an AgeException. Screenshots[Demo] The Code: import java.util.Scanner; class AgeException extends Exception {  public String toString()  {    return "AgeException Caught!";  } } public class AgeMargin {  public static void main(String []args)  {    int age;    Scanner s=new Scanner(System.in);    while(true)    {     try     {      System.out.println("Enter The Age: "); age=s.nextInt(); if(age>=18 && age<=24) { System.out.println("The age is w...

Shuffle the characters of a string in Java

Image
This is a program which accepts a string using the BufferdReader and InputStreamReader class, and then shuffle the characters present inside the string and generate a new string which is displayed in the console. Basically the characters of the string are stored in a Character List using the for each loop. Then the characters in that list is randomly removed and appended in a StringBuilder object output. Screenshots [Demo] The Code: import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; class Brain { public static void main(String []as)throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter The String: "); String input=br.readLine(); List<Character> characters = new ArrayList<Character>(); for(char c:input.toCharArray()){ ...

Shuffle an Integer Array In Java

Image
This program can be used to shuffle an integer array using java. Basically user gives an integer array then this array is converted to an arraylist of integer type. Then that array list is passed to a predefined function shuffle() from the collection class ! Screenshot: The Code import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Scanner; public class Shuffle { public static void main(String args[]) { List<Integer> dataList = new ArrayList<Integer>(); Scanner s=new Scanner(System.in); int n[]=new int[4]; for(int i=0;i<4;i++) { n[i]=s.nextInt(); dataList.add(n[i]); } /*Alternate Method: * for(int i=0;i<4;i++) dataList.add(s.nextInt()); */ Collections.shuffle(dataList); int[] num = new int[dataList.size()]; for (int i = 0; i < dataList.size(); i++) { num[i] = dataList.get(i); } System.out.println("Shuffled Array is : "); for (int i = 0; i < n...

Selection Sort Using Java

Image
This is a simple program to illustrate how to use selection sort for sorting integers using java code. Selection sort is an in-place sorting technique with time complexity of O(n2). Its time complexity remains same in all the 3 cases (i.e. best, average and worst) .This type of sorting is preferred where memory is limited. Screenshots: Program: import java.util.*; class Sorting { public static void selectionSort(int arr[], int size) { int i, j, pos=0,temp=0; for(i=0;i<size-1;i++) { pos=i; for (j = i+1; j < size; j++) { if (arr[j] < arr[pos]) pos = j; } // Swapping the elements temp = arr[i]; arr[i] = arr[pos]; arr[pos]= temp; } } public sta...

Check whether a point lies within a given circle using java

Image
                          Hello guys, this a very interesting yet simple concept. Here what we are going to learn is to check whether a point lies inside a given circle or not. Here we will use BufferedReader  to take inputs and compare between the two inputs. The result value we will display in the output. Sample Output: Program Code: import java.io.*; class Circle { double x, y; double radius; Circle(double x1,double y1, double radius) { x=x1; y=y1; this.radius=radius; } void check(double x2, double y2) { double d1=Math.sqrt((x-x2)*(x-x2)+(y-y2)*(y-y2)); if (radius>d1) { System.out.println("the point lies inside circle with "+x+","+y+" as centre"); } else System.out.println("the point doesnt lie inside the circle with "+x+","+y+" as centre and "+radius+" as radius"); } public static void main(String[] args) throws Exception { BufferedReader br=new BufferedRea...

Countdown Timer In Java Using Threading

Image
This is a simple Countdown program in Java which is done using threading. In this program the console is periodically cleared with a Console Object. The Basic design is to make the thread sleep for 1 sec till the give time is reached. The hours and Mins along with seconds are at first converted to seconds and a loop does the rest of the work ! Screenshot [Demo] The Code: import java.io.Console; import java.util.Scanner; public class timer { public static final char ESC = 27; public static void main(String as[])throws Exception { Scanner s=new Scanner(System.in); String tim; int hh,mm=0,ss=0; int sec; Console c = System.console(); if (c == null) { System.err.println("no console"); System.exit(1); } System.out.println("Enter In this format: \"HH:MM:SS\""); tim=s.next(); hh=Integer.parseInt(tim.substring(0,2)); mm=Integer.parseInt(tim.substring(3,5)); ss=Integer.parseInt(tim.substring(6,8)); sec=hh*3600+mm*60+ss; ...

JavaFX Application To Create Stage And Scene

Image
This is a simple program to create a JavaFX Application which displays Hello World ! Screenshots: The Code: package javafxapplication1; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.layout.StackPane; import javafx.stage.Stage; /** * * @author Matrix */ public class JavaFXApplication1 extends Application { @Override public void start(Stage primaryStage) { Button btn = new Button(); btn.setText("Say 'Hello World'"); btn.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { System.out.println("Hello World!"); } }); StackPane root = new StackPane(); root.getChildren().add(btn); Scene scene = new Scene(root, 300, 250); ...

Delayed Printing Using Threads In Java

Image
The bellow code snippet will perform the printing of the numbers in the loop till with a time gap of 1sec. You can modify the bellow snippet and add your creativity to try something new. Basically Thread.sleep()  makes the thread to wait for the specified time ! Screenshots[Demo]: The Code: class DelayPrint { public static void main(String args[]) { try { for(int n = 5; n > 0; n--) { System.out.println(n); Thread.sleep(1000);// Time Gap of 1 sec } } catch (InterruptedException e) { System.out.println("Main thread interrupted"); } } } Got Bugs, Drop them here ! And yes don't forget to subscribe us ! ;)

Moving Ball Using Applet and Timer Class

Image
This is a simple program using applet and Timer class in java which shows the simulation of a moving ball. Screenshot: The Code: import java.applet.Applet; import java.awt.*; import java.util.TimerTask; import java.util.Timer; // @author Ankur Raj public class Timer_1 extends Applet { Timer timer; int bx=100; int by=100; int bxv=2; int byv=2; int refresh=5; public void init() { timer =new Timer(); timer.schedule(new TimerTask() { public void run() { bx=bx+bxv; by=by+byv; repaint(); } },0,refresh); } public void paint(Graphics g) { g.fillOval(bx, by, 50, 50); } } Found bugs? Report us, we will happy to fix'em !