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
Showing posts with label java program. Show all posts
Showing posts with label java program. Show all posts
Java Program to Hibernate Windows Operating System
Do you want to hibernate your Windows computer using java program? This is a java program to hibernate Windows operating System. If you execute this java program, it will hibernate your Windows computer instantly. The following is the java code to hibernate Windows:
How to Launch a Application or Executable Using Java Code with Command Line Arguments
In this post, we shall see how to launch an application with its command line arguments using Java code. Most applications take path of a file as command-line argument to open it. If we give path of an image file to mspaint application as command-line argument, the image will be opened in paint. The following java program launches mspaint with a command-line argument which is a path to an image.
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
Are you thinking how to restart Windows from Java. You can restart Windows operating system by executing a system command. You can restart windows by executing the system command shutdown /r /t 1. The following Java code will restart the windows computer when executed.
try { Runtime.getRuntime().exec("shutdown /r /t 1"); } catch (IOException ex) {}
How to Schedule a Shutdown in Java - Java Code to Schedule a Shutdown
In this post, we will see how to schedule a shutdown in a computer using java program. For this, we execute the appropriate shutdown command after identifying the operating system. The following java code will schedule a shutdown after a 10 minute from execution of the code.
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 to Solve Tower of Hanoi Puzzle Problem
This is a java program to solve towers of hanoi puzzle problem. This simple java program gives solution for tower of hanoi problem with any number of disks. Tower of Hanoi is a mathematical game or puzzle. It is also called tower of brahma or Lucas' tower. There are three towers (or rods) and a number of disks of different diameters. Initially, The disks have hole at center so that it can slide on to the rods. Initially all disks are stacked on the first tower, say tower A, such that no disk is placed over a smaller disk. The goal or objective is to move all these disks from tower A (first tower) to tower C (third tower). But you should obey the following rules. The rules of towers of hanoi puzzle are:
Java Program to Find Power of a Number
This is a java program to calculate power of a given number. The inputs are the number and its exponent (power). For example, if you give m and n, the result is m^n. You may use built-in function Math.pow() or hard code it.
Using Built-in Function
import java.util.Scanner; public class Power{ public static void main(String[] args) { int m,n; Scanner sc=new Scanner(System.in); System.out.println("Enter number and its power"); m=sc.nextInt(); n=sc.nextInt(); System.out.printf("m^n = %.0f",(float)Math.pow(m,n)); } }
Without using Built-in function
import java.util.Scanner; public class Power{ public static void main(String[] args) { int m,n,i,p=1; Scanner sc=new Scanner(System.in); System.out.println("Enter number and its power"); m=sc.nextInt(); n=sc.nextInt(); for(i=0;i<n;i++) p*=m; System.out.printf("m^n = %d",p); } }
Java Program For Matrix Multiplication
This is a java program for Matrix Multiplication. To understand how it works, you should first know how matrix multiplication is done mathematically.
import java.util.Scanner; public class MatrixMult{ public static void main(String[] args) { int[][] m1=new int[10][10]; int[][] m2=new int[10][10]; int[][] prod=new int[10][10]; int i,j,k,r1,c1,r2,c2; Scanner sc=new Scanner(System.in); System.out.println("Enter number of rows and columns of first matrix:"); r1=sc.nextInt(); c1=sc.nextInt(); System.out.println("Enter number of rows and columns of second matrix:"); r2=sc.nextInt(); c2=sc.nextInt(); if(r2==c1) { System.out.println("Enter elements of First matrix (row wise):"); for(i=0;i<r1;i++) for(j=0;j<c1;j++) m1[i][j]=sc.nextInt(); System.out.println("Matrix1 is :"); for(i=0;i<r1;i++) { for(j=0;j<c1;j++) System.out.printf("%d ",m1[i][j]); System.out.printf("\n"); } System.out.println("Enter elements of Second matrix (row wise):"); for(i=0;i<r2;i++) for(j=0;j<c2;j++) m2[i][j]=sc.nextInt(); System.out.println("Matrix2 is:"); for(i=0;i<r2;i++) { for(j=0;j<c2;j++) System.out.printf("%d ",m2[i][j]); System.out.printf("\n"); } System.out.println("Product of the Matrices (M1 x M2):"); for(i=0;i<r1;i++) { for(j=0;j<c2;j++) { prod[i][j]=0; for(k=0;k<r1;k++) prod[i][j]+=m1[i][k]*m2[k][j]; System.out.printf("%d ",prod[i][j]); } System.out.print("\n"); } } else { System.out.println("Matrices can't be multiplied."); System.out.print("No. of columns of first matrix and no of rows of second are different."); } } }
Output
Enter number of rows and columns of first matrix: 2 2 Enter number of rows and columns of second matrix: 2 2 Enter elements of First matrix (row wise): 5 8 6 4 Matrix1 is : 5 8 6 4 Enter elements of Second matrix (row wise): 5 6 8 9 Matrix2 is: 5 6 8 9 Product of the Matrices (M1 x M2): 89 102 62 72
Java Program to Display Multiplication Tables of Given Number
This is a java program to display multiplication table of given number. For java program to display multiplication table of all numbers from 1 to 10, see this post:
Program to display multiplication table of all numbers from 1 to 10
1 * 5 = 5
2 * 5 = 10
3 * 5 = 15
4 * 5 = 20
5 * 5 = 25
6 * 5 = 30
7 * 5 = 35
8 * 5 = 40
9 * 5 = 45
10 * 5 = 50
import java.util.Scanner; public class Multiples{ public static void main(String[] args) { int n, i; Scanner sc=new Scanner(System.in); System.out.printf("Enter the number:"); n=sc.nextInt(); for(i=1; i<=10; ++i) System.out.printf("%d * %d = %d \n", i, n, n*i); } }
Output:
Enter the number:51 * 5 = 5
2 * 5 = 10
3 * 5 = 15
4 * 5 = 20
5 * 5 = 25
6 * 5 = 30
7 * 5 = 35
8 * 5 = 40
9 * 5 = 45
10 * 5 = 50
Java Program to Display Multiplication Tables of All Number from 1 to 10
This is a java program to display multiplication tables of all number from 1 to 10. To see java program to display multiplication table of given number only, see this program:
Program to Display Multiplication Table of Given Number
Program to Display Multiplication Table of Given Number
public class Multiples{ public static void main(String[] args) { int i,j; for(i=1;i<=10;i++) { for(j=1;j<=10;j++) System.out.printf("%d*%d=%d ",i,j,i*j); System.out.printf("\n"); } } }
Output:
1*1= 1 1*2= 2 1*3= 3 1*4= 4 1*5= 5 1*6= 6 1*7= 7 1*8= 8 1*9= 9 1*10=10 2*1= 2 2*2= 4 2*3= 6 2*4= 8 2*5=10 2*6=12 2*7=14 2*8=16 2*9=18 2*10=20 3*1= 3 3*2= 6 3*3= 9 3*4=12 3*5=15 3*6=18 3*7=21 3*8=24 3*9=27 3*10=30 4*1= 4 4*2= 8 4*3=12 4*4=16 4*5=20 4*6=24 4*7=28 4*8=32 4*9=36 4*10=40 5*1= 5 5*2=10 5*3=15 5*4=20 5*5=25 5*6=30 5*7=35 5*8=40 5*9=45 5*10=50 6*1= 6 6*2=12 6*3=18 6*4=24 6*5=30 6*6=36 6*7=42 6*8=48 6*9=54 6*10=60 7*1= 7 7*2=14 7*3=21 7*4=28 7*5=35 7*6=42 7*7=49 7*8=56 7*9=63 7*10=70 8*1= 8 8*2=16 8*3=24 8*4=32 8*5=40 8*6=48 8*7=56 8*8=64 8*9=72 8*10=80 9*1= 9 9*2=18 9*3=27 9*4=36 9*5=45 9*6=54 9*7=63 9*8=72 9*9=81 9*10=90 10*1=10 10*2=20 10*3=30 10*4=40 10*5=50 10*6=60 10*7=70 10*8=80 10*9=90 10*10=100
Decimal to BCD Converter in Java
In this post,we will see java program to convert decimal number to BCD representation. Binary-coded decimal (BCD) is a class of binary encodings of decimal numbers where each decimal digit is represented by a fixed number of bits, usually four. Thus the decimal digit 1 corresponds to 0001, 2 corresponds to 0010,.... 8 corresponds to 1000 and 9 corresponds to 1001. Therefore, decimal number 194 can be represented in BCD as 0001 1001 0100. It should be noted that 1010, 1011, 1100, 1101,1110 and 1111 are illegal in BCD. The following java program converts any decimal number to BCD. But in this program, for conversion each digit in the decimal, we use Integer.toBinaryString() method. So, i have added another program which does not use this method.
Program 1:
public static String toBCD(int num) { String BCD=""; while(num!=0) { int t=num%10; String tBCD=Integer.toBinaryString(t); while(tBCD.length()<4) { tBCD="0"+tBCD; } BCD=tBCD+BCD; num/=10; } return BCD; }
Program 2:
import java.util.Scanner; public class DecimalToBCD { static String digitToBcd(int digit) { String str=""; for(int i=3;i>=0;i--) { int d=(int) Math.pow(2,i); if(digit/d!=0) { str+="1"; digit-=d; } else str+="0"; } return str; } public static void main(String[] args) { Scanner sc=new Scanner(System.in); int decimal=sc.nextInt(); int digit; String BCD=""; while(decimal!=0) { digit=decimal%10; BCD=digitToBcd(digit)+" "+BCD; decimal/=10; } System.out.println("BCD is:"+BCD); } }The second program does not use any built in methods for conversion of decimal to BCD.
Java Program to Reverse a String
Here, we will see a java program to reverse a string. The string is read and is displayed in reverse order. Java program to display an input string in reverse order.
import java.util.Scanner; public class BMI { public static void main(String[] arg) { Scanner sc = new Scanner(System.in); System.out.println("Enter a string"); String s=sc.nextLine(); for(int i=s.length()-1;i>=0;i--) System.out.print(s.charAt(i)); } }
Java Program to Find Sum of First N Terms of an Arithmetic Progression
In this post we will see a java program to calculate sum of first n terms of an arithmetic progression. Arithmetic progression is also called AP (short for Arithmetic progression). The equation to find sum of first n terms of an arithmetic progression is as follows:
Now, we will see a java program to find sum of first n terms of an AP. The java program is as follows:
sum of first n terms = (n / 2) * (2 * a + (n - 1) * d)
Sum of first n terms of an AP (arithmetic progression) |
Now, we will see a java program to find sum of first n terms of an AP. The java program is as follows:
import java.util.Scanner; public class SumofAP { public static void main(String[] arg) { Scanner sc = new Scanner(System.in); System.out.println("Enter first term, common difference and n (number of terms)"); int a=sc.nextInt(),d=sc.nextInt(),n=sc.nextInt(); System.out.print("Sum: "+n*(2*a+(n-1)*d)/2); } }
Java Program to Display First N Terms of an Arithmetic Progression
This post contains java program to display first n terms of an AP (arithmetic progression). Generally the following equation to find nth term of arithmetic progression is used.
where a is first term and d is common difference. Using a loop we will display each term until we reach nth term. But here since we use a loop, for the program it is enough to keep on adding the common difference. We need not to use the above equation each time. The java program to display first n terms of a arithmetic progression (AP) is as follows:
nth term of AP = a + (n - 1) * d
where a is first term and d is common difference. Using a loop we will display each term until we reach nth term. But here since we use a loop, for the program it is enough to keep on adding the common difference. We need not to use the above equation each time. The java program to display first n terms of a arithmetic progression (AP) is as follows:
public class APTerms { public static void main(String[] arg) { int a,d,n; Scanner sc = new Scanner(System.in); System.out.println("Enter first term, common difference and n (number of terms)"); a=sc.nextInt()-(d=sc.nextInt()); n=sc.nextInt(); for(int i=0;i<n;i++) System.out.print(" "+(a+=d)); } }
Java Program to Display First N Terms of Geometric Progression
This post contains java program to display first n terms of a GP (geometric progression). Generally the following equation to find nth term of geometric progression is used.
Nth term of GP = a * r(n-1)Using a loop we will display each term until we reach nth term. But here since we use a loop, for the program it is enough to keep on multiplying with the common ratio. We need not to use the above equation each time. The java program to display first n terms of a geometric progression (GP) is as follows:
import java.util.Scanner; public class GPTerms { 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.print("\n"+a); for(int i=1;i<n;i++) System.out.print(" "+(a*=r)); } }
Java Program to Find Sum of First N Terms of Geometric Progression
In this post we will see a java program to calculate sum of first n terms of a geometric progression. Geometric progression is also called GP (short for Geometric progression). The equation to find sum of first n terms of a geometric progression is as follows:
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:
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)); } }
Java Program to Check Whether It Is Possible to Draw a Triangle with Given Sides
For existence of a triangle there is a condition. The condition is that the sum of the lengths of any two sides of a triangle must be greater than or equal to the length of the third side. If the sum of the lengths of any two sides of a triangle is equal to the length of the third side, it forms a triangle with zero area. The vertices are collinear in that case. Still we can say that the triangle exists. So, here we will see a java program to check whether a triangle exists or not with given sides. The program is as follows:
import java.util.Scanner; public class TriangleSide { public static void main(String[] arg) { Scanner sc=new Scanner(System.in); System.out.println("Enter the sides of triangle"); int a=sc.nextInt(),b=sc.nextInt(),c=sc.nextInt(); if(a+b>=c&&b+c>=a&&c+a>=b) System.out.println("possible"); else System.out.println("impossible"); } }
Four Different Java Programs to Swap Two Numbers Without a Third Variable
Swapping two numbers are done using a third variable. But it is often asked for programming interviews to swap two numbers without using a third variable. We will see four different programs in java to swap two variables without using a third variable. This type of questions are often asked in technical interviews.
In the third java code, we swap the numbers using bitwise XOR operation. The bitwise operator ^
is used in the program. The binary representation of the numbers, the bitwise xor operation on them and the result are shown in the c program as comments. For simplicity and convenience, we are representing numbers using only 5 bits. The real size of an integer in java is much larger. We show only the rightmost 5 bits. It is enough to illustrate the examples with small integers. The program is as follows:
In the fourth java program to swap two numbers without a temporary variable, we swap the numbers using a combination of addition, subtraction and bitwise NOT (inversion) operation. The bitwise operator ~ is used in the program. The binary representation of the numbers, the bitwise NOT operation on them and the result are shown in the java program as comments. The program is as follows:
Trick 1
In the first java program to swap two numbers without a third variable, we swap the values of the two variables in 3 steps which are simple addition and subtractions.
import java.lang.*; class Swapping { public static void main (String[] args) throws java.lang.Exception { int a=5,b=10; a=b+a; //now a =15 b=a-b; //now b= 5 a=a-b; // now a=10 (done) System.out.println("a = "+a+" b= "+b); } }
Trick 2
In the second java program to swap two numbers without a third variable, we swap them in a single statement. The statement contains an assignment, addition and subtraction.
import java.lang.*; class Swapping { public static void main (String[] args) throws java.lang.Exception { int a=10,b=30; a=a+b-(b=a); //10+30-(10) a becomes 30 // b is assigned with 10 in the same line of code System.out.println("a= "+a+" b= "+b); } }
Trick 3
is used in the program. The binary representation of the numbers, the bitwise xor operation on them and the result are shown in the c program as comments. For simplicity and convenience, we are representing numbers using only 5 bits. The real size of an integer in java is much larger. We show only the rightmost 5 bits. It is enough to illustrate the examples with small integers. The program is as follows:
import java.lang.*; class Swapping { public static void main (String[] args) throws java.lang.Exception { int a=8,b=12; /* a: 8 : 01000 b:12 : 01100 */ a=a^b; /* a: 01000 ^ b: 01100 a= 00100 (4) */ b=a^b; /*a: 00100 ^ b: 01100 b= 01000 (8) */ a=b^a; /* b: 01000 ^ a: 00100 a= 01100 (12) */ System.out.println("a= "+a+" b= "+b); } }
Trick 4
import java.lang.*; class Swapping { public static void main (String[] args) throws java.lang.Exception { int a=14,b=4; /* a: 14 : 1110 b: 4 : 0100 ~a: : 0001 ~b: : 1011 */ a=b-~a-1; /* b: 0100 - ~a: 0001 0011 - 1: 0001 0010 now a= 0010 */ b=a+~b+1; /* a: 0010 + ~b: 1011 1: 0001 now b: 1110 (14) ~b: 0001 */ a=a+~b+1; /* a: 0010 + ~b: 0001 1: 0001 now a: 0100 (4) */ System.out.println("a= "+a+" b= "+b); } }
Java Program For Spiral Matrix - Java Programming Interview Question
A spiral matrix is a matrix (two dimensional array) in which the elements are stored in a spiral fashion. Actually it is a normal NxN two dimensional array. But instead of accessing elements in row-wise or column-wise order, we access them in spiral order. i.e, in a 3x3 matrix the order of retrieval of elements is spiral order is as follows:
(0,0) (0,1) (0,2) (1,2) (2,2) (2,1) (2,0) (1,0) (1,1)
The following picture shows a 4x4 spiral matrix:
An question asked by zoho corporation during interview was to write a program to read a matrix spirally. In this post, we will answer this zoho interview question. Remember that the memory implementation is purely same as a normal matrix. The only difference here is the order in which we store elements to matrix or access elements in matrix. The following is the java program to read a spiral matrix. In thi s java program for spiral matrix, we just read the elements to the matrix. The elements entered by the user are entered into the matrix spirally. And the program finally displays the full matrix just as all normal matrices are displayed. Then you can see that the elements are not stored in the order as they were entered. You can see the spiral order in the matrix.
(0,0) (0,1) (0,2) (1,2) (2,2) (2,1) (2,0) (1,0) (1,1)
The following picture shows a 4x4 spiral matrix:
A 4x4 Spiral matrix |
An question asked by zoho corporation during interview was to write a program to read a matrix spirally. In this post, we will answer this zoho interview question. Remember that the memory implementation is purely same as a normal matrix. The only difference here is the order in which we store elements to matrix or access elements in matrix. The following is the java program to read a spiral matrix. In thi s java program for spiral matrix, we just read the elements to the matrix. The elements entered by the user are entered into the matrix spirally. And the program finally displays the full matrix just as all normal matrices are displayed. Then you can see that the elements are not stored in the order as they were entered. You can see the spiral order in the matrix.
import java.io.*; public class Spiral { public static void main(String args[]) { int a[][]=new int[10][10]; int o,cellcount,cc=0,c=0,i=0,j=0,g=1; try{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter the order of spiral matrix"); o=Integer.parseInt(br.readLine()); cellcount=o; System.out.println("\nEnter the elements:\n"); while(c<o*o) { cc=0; for(;cc<cellcount;j=j+g,cc++) a[i][j]=Integer.parseInt(br.readLine()); j=j-g; c+=cc; cc=0; i=i+g; cellcount--; if(c>=o*o) break; for(;cc<cellcount;i=i+g,cc++) a[i][j]=Integer.parseInt(br.readLine()); c+=cc; i=i-g; j=j-g; g*=-1; } System.out.println("\nThe spiral matrix is:"); for(i=0;i<o;i++) { System.out.print("\n"); for(j=0;j<o;j++) System.out.print(Integer.toString(a[i][j])+"\t"); } }catch(Exception ex){ex.printStackTrace();} } }
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
Java Program to Implement Broadcasting System Between a Server and Many Clients
Screenshot of broadcast server and clients using java |
Subscribe to:
Posts (Atom)