1.
Write a Java program that prompts the user for an integer and then prints out all the
prime n
Program:
import [Link];
public class PrimeNumbers{
public static void main(String arg[]){
int i,n,counter, j;
Scanner scanner = new Scanner([Link]);
[Link]("Required packages have been imported");
[Link]("A reader object has been defined ");
[Link]("Enter the n value : ");
n=[Link]();
[Link]("Prime numbers between 1 to 10 are ");
for(j=2;j<=n;j++){
counter=0;
for(i=1;i<=j;i++){
if(j%i==0){
counter++;
}
}
if(counter==2)
[Link](j+" ");
}
}
}
Output:
2. Write a Java program to multiply two given matrices.
public class Matrix{
public static void main(String args[]){
//creating two matrices
int a[][]={{1,1,1},{2,2,2},{3,3,3}};
int b[][]={{1,1,1},{2,2,2},{3,3,3}};
//creating another matrix to store the multiplication of two matrices
int c[][]=new int[3][3]; //3 rows and 3 columns
//multiplying and printing multiplication of 2 matrices
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
c[i][j]=0;
for(int k=0;k<3;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}//end of k loop
[Link](c[i][j]+" "); //printing matrix element
}//end of j loop
[Link]();//new line
}
}}
Output:
3. .Write a Java program that displays the number of characters, lines and words in a
text?
Program:
import [Link];
import [Link];
public class CountWord
{
public static void main(String[] args) throws Exception {
String line;
int count = 0;
//Opens a file in read mode
FileReader file = new FileReader("[Link] ");
BufferedReader br = new BufferedReader(file);
//Gets each line till end of file is reached
while((line = [Link]()) != null) {
//Splits each line into words
String words[] = [Link]("");
//Counts each word
count = count + [Link];
[Link]("Number of words present in given file: " + count);
[Link]();
}
}
Output
4. Generate random numbers between two given limits using Random class and print
messages according to the range of the value generated.
Program:
public class RandomNumber
{
public static void main( String args[] )
{
int min = 200;
int max = 400;
//Generate random double value from 200 to 400
[Link]("Random value of type double between "+min+" to "+max+ ":");
double a = [Link]()*(max-min+1)+min;
[Link](a);
//Generate random int value from 200 to 400
[Link]("Random value of type int between "+min+" to "+max+ ":");
int b = (int)([Link]()*(max-min+1)+min);
[Link](b);
}
}
Output: