try { Runtime.getRuntime().exec("shutdown /h"); } catch (IOException ex) {}
Tutorials, tips and tricks about java programming language. Answers for many doubts about java programming language. Answering many howtos. Sample java projects and source code, java games, java programs for java practical labs.
Search This Blog
Java Program to Hibernate Windows Operating System
How to Launch a Application or Executable Using Java Code with Command Line Arguments
try { Runtime.getRuntime().exec("C:\\Windows\\System32\\mspaint.exe \"C:\\Users\\Shareef\\Desktop\\flower.jpg\""); } catch (IOException ex) {}
Arguments are separated by spaces. If a command-line argument contains space within it (such as a space in a path), it is recommended to enclose it within brackets.
Java Code to Restart Windows
try { Runtime.getRuntime().exec("shutdown /r /t 1"); } catch (IOException ex) {}
How to Schedule a Shutdown in Java - Java Code to Schedule a Shutdown
String os=System.getProperty("os.name").toLowerCase(); String command; try { if(os.contains("windows")) { command="shutdown /s /t 600"; } else if(os.contains("linux")||os.contains("mac os x")) { command="shutdown -h +600"; } else throw new Exception("Unsupported OS"); Runtime.getRuntime().exec(command); }catch(Exception ex){ JOptionPane.showMessageDialog(null,ex.getMessage()); }
Java Program for Animated Solution for Tower of Hanoi Puzzle Problem
The solution of hanoi problem given by this program is always optimal. You can enter the number of disks first. This lets you solve puzzle of any level of difficulty. The program is as follows.
import java.awt.BorderLayout; import java.awt.Color; import java.awt.Graphics; import java.util.Random; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; public class HanoiAnimated extends JPanel{ static int tower[][];// the three towers' disks as stack static int top[];//top of the three stacks static int from,to;//moving 'from' tower number 'to' tower number static int diskInAir;//number of disk moved (1 to n) static int n,l,b,u; static Color colors[]={Color.BLUE,Color.CYAN,Color.GREEN,Color.MAGENTA,Color.ORANGE,Color.PINK,Color.RED,Color.YELLOW}; public HanoiAnimated() { tower=new int[3][10]; top=new int[3]; } static void push(int to, int diskno) //putting disk on tower { tower[to-1][++top[to-1]]=diskno; } static int pop(int from) //take topmost disk from tower { return(tower[from-1][top[from-1]--]); } Color getColor(int disknum) { return colors[disknum%8]; } void drawStill(Graphics g) { int j,i,disk; g.clearRect(0,0,getWidth(),getHeight()); for(j=1;j<=3;j++) { //draw tower g.setColor(Color.GRAY); g.fillRoundRect(j*l,u,5,b-u,1,1); //draw all disks on tower for(i=0;i<=top[j-1];i++) { disk=tower[j-1][i]; g.setColor(getColor(disk)); g.fillRect(j*l-15-disk*5,b-(i+1)*10,35+disk*10,10); } } } void drawFrame(Graphics g,int x,int y) { try{ drawStill(g); g.setColor(getColor(diskInAir)); g.fillRect(x-15-diskInAir*5,y-10,35+diskInAir*10,10); Thread.sleep(60); }catch(InterruptedException ex){} } void animator(Graphics g) //to show the movement of disk { int x,y,dif,sign; diskInAir=pop(from); x=from*l; y=b-(top[from-1]+1)*10; //taking disk upward from the tower for(;y>u-20;y-=8) drawFrame(g, x, y); y=u-20; dif=to*l-x; sign=dif/Math.abs(dif); //moving disk towards a target tower for(;Math.abs(x-to*l)>=24;x+=sign*12) drawFrame(g, x, y); x=to*l; //placing disk on a target tower for(;y<b-(top[to-1]+1)*10;y+=8) drawFrame(g, x, y); push(to,diskInAir); drawStill(g); } void moveTopN(Graphics g, int n, int a, int b, int c) throws InterruptedException //Move top n disk from tower 'a' to tower 'c' //tower 'b' used for swapping { if(n>=1) { moveTopN(g,n-1,a,c,b); drawStill(g); Thread.sleep(700); from=a; to=c; //animating the move animator(g); moveTopN(g,n-1,b,a,c); } } public static void main(String[] args) { int i; String s=JOptionPane.showInputDialog("Enter number of disks"); n=Integer.parseInt(s); HanoiAnimated ha=new HanoiAnimated(); //setting all tower empty for(i=0;i<3;i++) top[i]=-1; //putting all disks on tower 'a' for(i=n;i>0;i--) { push(1,i); } JFrame fr=new JFrame(); fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); fr.setLayout(new BorderLayout()); fr.setSize(640,360); fr.add(ha); ha.setSize(fr.getSize()); fr.setVisible(true); l=ha.getWidth()/4; b=ha.getHeight()-50; u=b-n*12; //start solving try{ ha.moveTopN(ha.getGraphics(),n,1,2,3); }catch(Exception ex){} } }
Java Program to Solve Tower of Hanoi Puzzle Problem
Java Program to Find Sum of First N Terms of Geometric Progression
sum= a*(1-r^n)/(1-r)
sum of first n terms of geometric progression |
Now, we will see a java program to find sum of first n terms of a GP. There is a case in which the above equation fails. When r (common ratio) is 1, the above equation won't work. Then every term in the GP will be same as first term. Therefore, in that case, the sum is a*n. The program is as follows:
import java.util.Scanner; public class SumGP { public static void main(String[] arg) { Scanner sc=new Scanner(System.in); System.out.println("Enter first term, common ratio and n (number of terms)"); int a=sc.nextInt(),r=sc.nextInt(),n=sc.nextInt(); System.out.println((r==1)?"Sum is:"+a*n:"Sum is:"+(float)a*(1-Math.pow(r,n))/(1-r)); } }
Body Mass Index Calculator Using Java - Java Application Code
import java.util.Scanner; public class BMI { public static void main(String[] arg) { Scanner sc=new Scanner(System.in); System.out.println("Enter weight in kgs and height in meters"); float bmi=sc.nextFloat()/(float)Math.pow(sc.nextFloat(),2); String s=(bmi<18.5)?"Underweight":(bmi<25)?"Normal weight":(bmi<30)?"Overweight":"Obesity"; System.out.println("bmi: "+bmi+" "+s); } }
Calculate your BMI here
Weight (in kg): | |
Height (in meters): | |
Java Program To Send an XML File From Server to Client and Display it as Table
XML parsed and displayed as a table |
Write a Program to read an xml file stored in the server. A client connected to the server gets the file and display the contents in a table using swing. The xml file contains details of books with the following fields.
Temperature Converter Program Using Java - Celsius, Kelvin, Fahrenheit, Reaumur and Rankine
Java Temperature Converter Program |
will see a good temperature converter code. This java temperature conversion application converts temperature between Celsius, Kelvin, Fahrenheit, Reaumur and Rankine scales. The java program for this temperature consists of methods for:
- Celsius to Fahrenheit Conversion
- Celsius to Kelvin Conversion
- Celsius to Reaumur Conversion
- Celsius to Rankine Conversion
- Fahrenheit to Celsius Conversion
- Fahrenheit to Kelvin Conversion
- Fahrenheit to Reaumur Conversion
- Fahrenheit to Rankine Conversion
- Kelvin to Celsius Conversion
- Kelvin to Fahrenheit Conversion
- Kelvin to Reaumur Conversion
- Kelvin to Rankine Conversion
- Reaumur to Celsius conversion
- Reaumur to Kelvin conversion
- Reaumur to Fahrenheit conversion
- Reaumur to Rankine conversion
- Rankine to Celsius conversion
- Rankine to Kelvin conversion
- Rankine to Fahrenheit conversion
- Rankine to Reaumur conversion
How to Filter Filetypes using File Extensions in JFileChooser - Java File Chooser
Screenshot of following example java program |
How to Get Operating System Information in Java
Using java, you can gather some information about the operating system of the computer system on which the code is running. That us java provides some API classes that will help you to know about the operating system of the computer on which your application program is running. You can use System.getProperty() method for this purpose. There are some system property keys (strings) which can be used to get the respective information. The parameter to the System.getProperty() method is a string, the property key. The following values for the parameter string will give operating system related informations.
"os.arch"
Operating system architecture
"os.name"
Name of the operating system.
"os.version"
Version of Operating system.
Usage examples:
The following java program displays the Operating system related informations using getProperty() method.How to Make a Timer Controlled Progress Bar in Java
timer controlled progress bar in java |
JProgressBar to create progress bars. It can have horizontal or vertical orientation. We can set the maximum and minimum values for JProgressBar. It can also have an indeterminate state in which the progressbar does not show a definite value and plays an animation to show that the process is in progress. JProgressBar can be used in indeterminate mode when neither can you determine how long a process would take to complete nor can you track its progress. In some other cases, you may have to use timers. Java provides a Timer class (Java.util.Timer). But you can create a very simple and flexible timer if you want. If the timer does not have crucial importance, you can use a thread that sleeps for every one second as a timer. I have been using such threads as timers for a long time and never failed. Such timers may fail (although very rarely) when the processor has very heavy workload.
Java Program to Send Image between Computers using UDP and Display it
Java program to send image file over network using UDP |
picture (image) from a computer to another via network using UDP protocol and to display it at the receiving end. Simply, this is the java code to make a java application which can send images from one computer to another over a network. The program uses UDP (User Datagram Protocol). For both the computers (on either ends) the same code is enough. This app can act as a image sender or a receiver. The program uses a Progress bar (JProgressBar) to show the progress of the data transfer. Remember, transferring files over UDP is not easy because UDP does not guarantee ordered delivery, and not even successful delivery. So, here in this program, to ensure ordered delivery, the sender sends next chunk of data (DatagramPacket) only after receiving an acknowledgement for last sent packet. For acknowledgement, i used a string "ACK".
Chat Room Application using UDP in Java
Java Chat room application using UDP |
Protocol) for chatting. The application gives you to options. One is to create a new chat room and the other is to join a chat room. The one who creates the chat room acts as a server for the chatroom. Others can join this chatroom id they know his IP address. This simple java chat room application is enough for server and clients. The GUI is basic one and not too attractive. Also i have used JOptionPane to reduce code. You may make improvements to the code. The chat rooms are not password protected. Anyone who know the server's IP address are granted access to the chat room. If you wish, you may improve the program. This Group chat application using java can be used in Local area networks. This code for java group chat program can be modified to enable chatting in multiple chat rooms. Try it.
How to download a file from internet Using java if URL is Given
How to Get Path to Temp Directory for Current User in Java
In some cases, you may need to create temporary files. It is preferred to create temporary files and folders in the current user's temporary folder (temp directory) because, the user will be able to clean unwanted files. To get the path to the temp folder of current user, java provides a property key to be used with
System.getProperty(). it is
"java.io.tmpdir".
The following code displays the path to the temporary folder for the current user.
How to Get Center Point of Screen in Java
The LocalGraphicsEnvironment in Java will give you the center point of the display or screen. There is a static method getLocalGraphicsEnvironment() in GraphicsEnvironment class. To get the center point of the screen, you may use the following java code:
You should include these import statements in the file.
How to Set JFrame in Center of Screen
To set JFrame in center of Just call this.setLocationRelativeTo(null); in constructor of the JFrame. If you are using Netbeans IDE, it should be after calling initComponents() method. But if you call setLocation() method of JFrame after this, your JFrame will get relocated.
In most cases this works and this is enough. if you want to get the center point of the screen, just refer to the following post:
How to Get Center Point of Screen in Java
How to Set Background Color of a JFrame in Java
Keep in mind that you have to import java.awt.Color; You can use the first one if you don't know RGB values of the desired color. Most common colors are defined as constants in Font class. If you know the RGB color values for your desired color, you can use the second example.