[Read more…] about Infinite For loop Example | Java Examples
Jump Statements in Java Example
In Java, Jump statements are used to unconditionally transfer program control from one point to elsewhere in the program. Jump statements are primarily used to interrupt loop or switch-case instantly. Java supports three jump statements: break, continue, and return. [Read more…] about Jump Statements in Java Example
Print all the Prime Numbers up to 100
we have seen how to test whether a given number is prime or not. The program segment given below uses a for loop to test each number in a given range and print it if it is prime. [Read more…] about Print all the Prime Numbers up to 100
Prime Number Program in Java Using BufferedReader Example.
Nested For Loop in Java Example
Nested loop means one loop inside the other. When a loop is written inside the other loop, a condition is essential to maintain: the inner loop will not cross the boundary of the outer loop. That is, the inner loop will begin and end inside the outer loop. We can have any number of loops one inside the other. [Read more…] about Nested For Loop in Java Example
Enter 10 Number and Print the Number of Positive, Negative and Zeros Number
In this example we use BufferedReader class for Reading text from a character-input stream. After Enter any 5 Number we check if number ==0 then is zero if number greater than 0 then it is positive other wise negative. [Read more…] about Enter 10 Number and Print the Number of Positive, Negative and Zeros Number
StringBuffer Reverse() in Java Example
StringBuffer reverse () : This method reverse the character sequence contained in the string buffer. In other words, the first character becomes the last, the second character becomes the second last and so on. For example, The Word “welcome” after reverse.
S1. reverse () will return emoclew.
Here is the Java Example for StringBuffer reverse():
public class StringBufferReverse
{
static void ReverseString()
{
String a ="Dinesh Thakur";
System.out.println("\nOriginal String : " + a);
StringBuffer b = new StringBuffer(a).reverse();
System.out.println("Reverse character string : "+b);
}
public static void main(String[] args)
{
ReverseString();
}
}
A string “Dot saw I was Tod” how converted into “doT saw & was toD”?
Algorithm For ReverseIT:
step 1: set s=”Dat saw 1was Tad”
step 2: set len=s.length()
step 3: create two character array c[], cl[] of size len
step 4: initialize i=0
step 5: repeat through step-7 while (i < len)
step 6: c[i]=s. charAt(i)
step 7: i=i+ 1
step 8: initialize j=0
step 9: repeat through step-11 while (j < len)
step 10: c1[j]=c[len-1-j]
step 11: j=j+ 1
step 12: string sl =new String(c1)
step 13: print sl
step 14: Exit
Here is the Java Example for ReverseIT:
public class ReverseIT
{
public static void main(String[] args)
{
String s="Dot saw I was Tod";
int len=s.length();
char[]c=new char[len];
char[]c1=new char[len];
for(int i=0;i<len;i++)
{
c[i]=s.charAt(i);
}
for(int j=0;j<len;j++)
{
c1[j]=c[len-1-j];
}
String sl=new String(c1);
System.out.println(sl);
}
}
CharAt() in Java Example
charAt():- This is a predefined method of String class present in java.1ang package. It used to extract a specify character from a string by the particular index supplied by the programmer and the index must be within the length of the String.
Syntax:- public char charAt(int index)
Algorithm for CharAt():
step 1: read string a
step 2: initialize i=0
step 3: repeat through step-5 while (i < a.length())
step 4: print i is a.charAt(i)
step 5: i=i+ 1
step 6: exit
Here is the Java Example for CharAt():
import java.util.*;
public class charAt
{
static void AtChar()
{
System.out.print("Enter a Sentence : ");
Scanner s=new Scanner(System.in);
String a=s.nextLine();
for (int i=0; i<a.length();i++)
{
System.out.println("char " + i + " is " + a.charAt(i) );
}
System.out.println();
}
public static void main(String[] args)
{
AtChar();
}
}
String Sorting in Java Example
Algorithm for String Sorting:
step 1: Set two String variables sl,s2, four integer variables count1, count2, size 1, size2 as static
step 2: Read sl,s2
step 3: Set String variable s3=sl.toLowerCase()
step 4: Set String variable s4=s2.toLowerCase()
step 5: Set size1=s3.length()
step 6: Set size2=s4.length()
step 7: Set byte array b1=s3.getBytes()
step 8; Set byte array b2=s4.getBytes()
step 9: Initialize k=97
step 10: repeat through step-30 while (k< 123)
step 11: countl =0
step 12: count2= 0
step 13: Initialize i=0
step 14: repeat through step-16 while (i< size1)
step 15: if b1[i]==k then count1 =count1 +1
step 16: i=i+ 1
step 17: Initialize j=0
step 18: repeat through step-20 while (j< size2)
step 19: if b2[j]==k then count2=count2+ 1
step 20: j=j+ 1
step 21: if countl > count2 then execute following codes else goto step-27
step 22: initialize a=0
step 23: repeat through step-25 while (a< count1)
step 24: print ((char)k)
step 25: a=a+ 1
step 26: goto step- 31
step 27: initialize x=0
step 28: repeat through step-30 while (x< count2)
step 29: print ((char)k)
step 30: x=x+ 1
step 31: Exit
Here is the Java Example for String Sorting:
import java.util.Scanner;
public class StringSorting
{
public static String sl;
public static String s2;
public static int count1,count2;
public static int size1,size2;
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.print("Enter 1st String :");
sl=s.nextLine();
System.out.print("Enter 2nd String :");
s2=s.nextLine();
String s3=sl.toLowerCase();
String s4=s2.toLowerCase();
size1=s3.length();
size2=s4.length();
byte bl[]=s3.getBytes();
byte b2[]=s4.getBytes();
System.out.println(s3+" "+s4);
System.out.println("The Sorted String Output is ");
for(int k=97;k<123;k++)
{
count1=0;
count2=0;
for(int i=0;i<size1;i++)
{
if(bl[i]==k)
{
count1++;
}
}
for(int j=0;j<size2;j++)
{
if(b2 [j]==k)
{
count2++;
}
}
if(count1>count2)
{
for(int a=0;a<count1;a++)
{
System.out.print((char)k +" ");
}
}
else
{
for(int x=0;x<count2;x++)
{
System.out.print((char)k+" ");
}
}
}
}
}
Count How Many Times a Character is Present in a String
Algorithm for CharacterInString:
step 1: create an integer array a[] of size 26
step 2: initialize i=0
step 3: repeat through step-5 while (i < 26)
step 4: a[i]= 0
step 5: i=i+ 1
step 6: read string st
step 7: set string st1=st.toLowerCase()
step 8: set a character array bt=stl.toCharArray()
step 9: initilaize j=0
step 10: repeat through step-l6 while (j < stl.length())
step 11: reset i=0
step 12: repeat through step-l5 while (i < 26)
step 13: set k=i+97
step 14: if(byte)bt[j]==k then a[i]=a[i]+ 1
step 15: i=i+ 1
step 16: j= j+ 1
step 17: initialize i=0
step 18: : repeat through step-20 while (i < 26)
step 19: if a[i]!=0 then print (char)(i+97) is present in string for a[i] times
step 20: i=i+ 1
step 21: Exit
Here is the Java Example for CharacterInString:
import java.util.Scanner;
public class CharacterInString
{
public static void main(String args[])
{
int a[]=new int[26];
for(int i=0;i<26;i++)
{
a[i]=0;
}
Scanner s=new Scanner(System.in);
System.out.print("Enter the String : ");
String st=s.nextLine();
String st1=st.toLowerCase();
char bt[]=st1.toCharArray();
for(int j=0;j<st1.length();j++)
{
for(int i=0;i<26;i++)
{
int k=i+97;
if((byte)bt[j]==k)
{
a[i]++;
}
}
}
for(int i=0;i<26;i++)
{
if(a[i]!=0)
System.out.println((char) (i+97)+ " is present ! "+ a[i]+" times");
}
}
}
toCharArray() in Java Example
toCharArray():-This method is a predefined method of String present in lang package.It used to convert a String into array of character.
Syntax:-public char[] toCharArray()
Algorithm for toCharArray() in java:
step 1: read string s1
step 2: create a character array c[]=sl.toCharArray()
step 3: initialize i=0
step 4: repeat through step-6 while (i < s1.length)
step 5: print (byte)c[i]
step 6: i=i+ 1
step 7: Exit
Here is the Java Example for toCharArray() in java:
import java.util.Scanner;
public class toCharArray
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.print("Enter the String : ");
String s1=s.nextLine();
char c[]=s1.toCharArray();
for(int i=0;i<s1.length();i++)
{
System.out.println(c[i]+" = "+(byte)c[i]);
}
}
}
Enter a String from keyboard and check whether it Palindrome or Not
Length():-This method is a predefined method of String class present in java. Lang package. It is used to determine the length of string and return type of this method is int type. [Read more…] about Enter a String from keyboard and check whether it Palindrome or Not
Sum of first n Sequence Numbers in Java Example
Print the table of an input number up till 10 times in Java Example
Print n Even Numbers in Java Example
Print n Sequence Numbers in Java Example
Odd Numbers from 1 To 100 in Java Example
For Loop | Java Examples
The for loop enables code to execute repeatedly until a boolean expression evaluates to false.
Syntax:
for (initialization; expression; modification)
{
statement(s);
}
The keyword for begins the loop. The parentheses contain an initialization, an expression, and a modification. The initialization is used to initialize a variable with certain value. Initialization is followed by a semicolon (;), followed by an expression. This is followed by another semicolon and then modification. Modification is basically an increment or decrement statement. When a for loop is encountered, initialization is first executed, and then the expression. If it evaluates to true, the statement or block following the for statement is executed. When the end of the body is reached, modification is executed. The expression is then evaluated again. If it is false, execution continues with the statement following the for loop. If it is true, the body of the for loop is executed again.
/* Print the sequence no from 20 to 30 */
class ForSequence
{
public static void main(String args[] )
{
int i;
for(i=20;i<=30;i++)
{
System.out.print(i + ” “);
}
}
}
The variable i is assigned a value 20. Since 20 <=30, the body of the for loop is executed, displaying the value of i I.e. 20 on the screen. Then i++ is executed, which increases value of i to 21. This value of 21 is compared with 30. Since 21 <=30, again the body of for loop will be executed replacing 21 on the screen. Again, the process is repeated until i becomes >30. The initialization of variable i of for loop shown above can be done before the beginning of for loop:
i=20;
for(;i<=30;i++)
{
System.out.print(i + ” “);
}
We can even write the increment statement of the loop as shown:
i=20;
for(;i<=30;)
{
System.out.print(i + ” “);
i++;
}
Even the logical expression can be avoided written at the top and can be included in the body of the loop as shown:
i=20;
for(;;)
{
If( i<=30) break;
System.out.print(i + ” “);
i++;
}
Above for loop i.e. for(;;) is considered as infinite for loop. break statement is used for coming out of the loop
Do-while Loop in Java, do while syntax Java Example
The do loop enables us to repeatedly execute a block of code until a boolean expression evaluates to false. It is almost identical to the while loop with the difference that here the logical expression is evaluated at the bottom of the loop rather than the top. This means that the contents of the loop will execute at least once.
Syntax:
do
{
statement(s);
} while (expression);
The keyword do begins the do construct. This is followed by a statement or a block. Next is the keyword while, followed by the parentheses containing an expression that must evaluate to a boolean value i.e. true or false.
When a do loop is encountered, the statement or block following the do keyword is executed. When the do loop body completes, logical expression is evaluated. If it is false, execution will continue with the next statement following the do loop. If it is true, the body of the do loop will be executed again. The body will continue to execute until the expression evaluates to false.
/* Print the sequence numbers from 1 to 10 using do while loop */
class DoWhile
{
public static void main(String args[] )
{
int i;
i=1;
do
{
System.out.print(i+ ” “);
i++;
}while(i<=10);
}
}
While Loop in Java Example
The while loop is a construct that repeatedly executes a block of code as long as a boolean condition remains true. The logical expression in while loop is evaluated first. If the logical expression evaluates to false, the body of while loop will not execute even once. If the logical expression in while evaluates to true, the statements in the body of while loop are executed. After executing the body, control jumps again at the top to recheck whether the boolean expression is still true or not. The body of the loop will continue to execute until the expression evaluates to false. When the logical expression becomes false, control continues the execution with the statements following while loop.
Syntax:
while ( expression)
{
statement(s);
}
/* Print Sequence No from 10 to 1 using while loop */
class SequenceWhile
{
public static void main(String args[] )
{
int i;
i=10;
while(i>=1)
{
System.out.print(i +”,”);
i–;
}
}
}
As we can see in above program, the value of variable i is initially set to 10. In while loop, the logical expression i >=1 evaluates to true (because 10 >1), the body of the loop will execute and 10 will be displayed on the screen. Then the value of variable I is decremented by 1 making it 9. Again, the control goes to the top and checks whether the expression i >=1 is still true or not. Since 9 >1, the expression evaluates to true, control will again execute the body of loop displaying value 9 on the screen. Again, the value of i is decremented by 1 making it 8. Again the control goes to the top to check whether the logical expression i>=1 is still true or not. Hence, the body of 100 will continue to execute for the time value of variable i is >= 1.
/* Print even numbers from 20 to 40 using while loop */
class EvenNumberWhile
{
public static void main(String args[] )
{
int i;
i=20;
while(i<=40)
{
System.out.println(i);
i+=2;
}
}
}
Nested Switch Statements Java Example
The switch statement is a multi-way decision making statement which selects one of several alternatives based on the value of an integer variable or expression. The switch statement is mainly used to replace multiple if-else-if statement. The if-else-if statement causes performance degradation as several conditions need to be evaluated before a particular condition is satisfied.
Its syntax is
switch (expression)
{
case constant l statement(s)1; [break ;]
case constant 2 statement(s)2;[break;]
……………………………………………………
case constant n : statement(s)n;[break ;]
default statement(s);
}
This structure starts with a keyword switch followed by the expression enclosed in the parentheses. The expression can result in a constant value of type char, byte, short ,int or an enumeration constant but not of type long, float or double. Possible switch options are defined by one or more case values also known as case labels. A case label consists of the case keyword followed by a constant value i.e. the value which will select the case, followed by a colon. Each case label must be of the same data type as that of the switch expression. The value of the expression is compared with each of the case labels (integer/character constants) in the order they appear in the switch statement. If a match occurs then the statement(s) corresponding to that case are executed. If no match occurs with any of the case then only the statement(s) following the default case are executed. The default part is optional in the switch statement.
Each case can contain zero, one or more program statements. Unlike other control structures the block of statements corresponding to a case are not required to be enclosed in curly braces.
A case is normally terminated with a break statement. When a break statement is encountered, the switch statement is exited and program continues with the next executable statement following the switch statement. In some situations, a case may not be terminated with a break statement then the statements for the next case in the sequence will be executed as well as through to the other statements until another break statement is found or end of the switch statement is reached. The last case statement need not have a break statement as the program control automatically transfers out of the switch statement.
/* Enter a character between a and d and print its corresponding word using switch command. that is, print Apple if a is entered, Bat if b is entered and so on. */
import java.io.*;
class NestedSwitchStatements
{
public static void main(String args[] )
throws IOException
{
BufferedReader k=new BufferedReader(new InputStreamReader
(System.in));
char h;
System.out.print(“Enter a character between a and d : “);
h=(char)k.read();
switch (h)
{
case ‘a’ :
case ‘A’:
System.out.println(“Apple”);
break;
case ‘b’ :
case ‘B’:
System.out.println(“Bat”);
break;
case ‘c’ :
case ‘C’:
System.out.println(“Cat”);
break;
case ‘d’ :
case ‘D’:
System.out.println(“Dog”);
break;
default :
System.out.println(“Value out of range. Please enter between a and d”);
}
}
}
/* Enter a month and year and display the number of days in that month. Use switch statement. */
import java.io.*;
class SwitchStatements
{
public static void main(String args[] )
throws IOException
{
BufferedReader k=new BufferedReader(new InputStreamReader
(System.in));
String h;
int m,y,nod;
System.out.println(“Enter month number : 1 for Jan, 2 for Feb …”);
h=k.readLine( );
m=Integer.parseInt(h);
System.out.println(“Enter year”);
h=k.readLine( );
y=Integer.parseInt(h);
nod=0;
switch (m)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
nod =31;
break;
case 4:
case 6:
case 9:
case 11:
nod =30;
break;
case 2:
if (((y % 4 == 0) && !(y % 100 == 0)) || (y % 400 == 0) )
nod = 29;
else
nod = 28;
break;
default:
nod = 0;
break;
}
System.out.println(“Number of days in ths month are ” +nod);
}
}
Switch Statement in Java Example
When there is requirement of several branching i.e. if we need several if statements, it is better to use switch statement. In other words, switch is a variation of if statement which performs multiway branching.
Syntax:
switch (expression)
{
case value:
statement(s) ;
break;
case value:
statement(s);
break;
default:
statement(s);
break;
}
The keyword switch begins the switch construct. The parentheses contain expression which may be a byte, a char, a short, or an int. Next is a required {, followed by any number of constructs that begin with the keyword case and end with break, with any number of statements in between. Then, there is an optional keyword called default which ends with break. Finally, a required} completes the case statement.
The case statement works by evaluating the expression and then scanning down the case statements until a match is found. When the match is found, the corresponding group of statements between the case and break will be executed. break statement is for exiting from switch construct. If no matches are found and a default is present, the group of statements associated with default will be executed. If no default is present and no match is found control jumps to the statements following switch command.
Note: When the statement of any case is executed and we forget to place break, then control will go into following case construct and executes its statements also. It keeps on executing all the statements of each case construct one after the other until a break is encountered or switch gets over.
Example:
switch(k)
{
case ‘a’ : System.out.println(“Apple “);
break;
case ‘b’ : System.out.println(“Bat”) ;
break;
default : System.out.println(“Please enter a character”);
}
In above example, the control will jump to respective statement depending on the value of the variable k. If the value of k is ‘a’, then Apple will be printed on the screen. break after System.out.println takes the control out of the switch statement. If break is not included, control will also execute the case statement following it i.e. it will also print Bat, even though the value of k is ‘a’. This means that when case is true, then its statements are executed followed by other case statements until control encounters break statement.
If the value of k is neither ‘a’ nor ‘b’, then control will execute default statement displaying “Please enter a character” on the screen.
Look at the following example: Here, we have removed all break statements
switch(k)
{
case ‘a’ : System.out.println(“Apple”);
case ‘b’ : System.out.println(“Bat”);
case ‘c’ : System.out.println(“Cat”);
default: System.out.println(“Please enter a character”);
}
In above example, if the value of k is ‘a’, it will print:
Apple
Bat
Cat
Please enter a character
This is because after p~inting Apple, control will continue executing another case
statement in absence of break statement
If value of k is ‘b’, it will print
Bat
Cat
Please enter a character
If value of k is ‘c’, it will print
Cat
Please enter a character
Features of the switch statement:
1. The switch differs from the if statements in the sense that switch can only test for equality, whereas if can evaluate any type of logical expression. That is, the switch looks only for a match between the value of the expression and one of its case constants.
2. No two case constants in the same switch can have identical values.
3. A switch statement is more efficient than a set of nested if statements.
When it compiles a switch statement, the Java compiler will inspect each of the case constants and create a “jump table” that it will use for selecting the path of execution depending on the value of the expression. It is for this reason that switches statement runs much faster than the sequence of if else.
To demonstrate the circumstances where switch performs better then the series of if statements, lets look at the following two programs. First program is written with the help of if statement and the same program is then written with switch statement
/* Enter a value between 1 and 4 and print it in words */
import java.io.*;
class SwitchExample
{
public static void main(String args[] )
throws IOException
{
BufferedReader k=new BufferedReader(new InputStreamReader
(System.in));
String h;
int n;
System.out.println(“Enter a value between 1 and 4 “);
h=k.readLine( );
n=Integer.parseInt(h);
if(n==1)
{
System.out.println(“One”);
}
if(n==2)
{
System.out.println(“Two”);
}
if(n==3)
{
System.out.println(“Three”);
}
if(n==4)
{
System.out.println(“Four”);
}
}
}
Now, the same above program is also done with switch statement for comparison
/* Enter a value between 1 & 4 and print it in words using switch command. */
import java.io.*;
class SwitchExample
{
public static void main(String args[] )
throws IOException
{
BufferedReader k=new BufferedReader(new InputStreamReader
(System.in));
String h;
int n;
System.out.println(“Enter a value between 1 and 4 “);
h=k.readLine( );
n=Integer.parseInt(h);
switch(n)
{
case 1:
System.out.println(“One”);
break;
case 2:
System.out.println(“Two”);
break;
case 3:
System.out.println(“Three”);
break;
case 4:
System.out.println(“Four”);
break;
default :
System.out.println(“The value is above Four”);
}
}
}
From above two programs, we can easily see that using switch statement is more handy and readable as compared to using series of if statements
Nested If in Java Example
When we have if or if else statement within another if construct or else construct, we call it nested if.
Syntax:
if(condition)
{
if(condition)
statement;
[else statement; ]
}
else
{
if(condition)
statement;
[else statement;]
}
As, we can see in above syntax that else is optional (enclosed within []). We can have any number of if else within if or else section i.e. we can have if else statements nested to any level.
Secondly, in nested if statements, the internal if else statements in if section will be evaluated only in case the logical expression of outer if statement evaluates to true. Similarly, the if else statements of else section will be checked for validity only if the logical expression of outer if statement evaluate to false.
/* Enter three values a,b and c and print largest of them */
import java.io.*;
class Largest
{
public static void main(String args[] )
throws IOException
{
BufferedReader k=new BufferedReader(new InputStreamReader
(System.in));
String h;
int a,b,c;
System.out.print(“Enter three Values :”);
h=k.readLine( );
a=Integer.parseInt(h);
h=k.readLine( );
b=Integer.parseInt(h);
h=k.readLine( );
c=Integer.parseInt(h);
if(a>=b)
{
if(a>=c)
{
System.out.println(“Largest is “+a);
}
else
{
System.out.println(“Largest is “+c);
}
}
else
{
if(b>=c)
{
System.out.println(“Largest is “+b);
}
else
{
System.out.println(“Largest is “+c);
}
}
}
}
If Else If Ladder, if..else ….if else statement in Java Example
A common programming construct that is based upon a sequence of nested ifs is the if-else-if ladder.
Syntax:
if(condition)
statement;
else
if(condition)
statement;
else
if(condition)
statement;
else
statement;
The if Conditional statements is executed from top down approach. As soon one of the conditions of if is true, then the associated statement with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.
/* Enter marks and print First div if marks>=60 Second div if marks >=45 and <60 otherwise print Third division */
import java.io.*;
class IfElseIfLadder
{
public static void main(String args[] )
throws IOException
{
BufferedReader k=new BufferedReader(new InputStreamReader
(System.in));
String h;
int m;
System.out.print(“Enter marks : “);
h=k.readLine( );
m=Integer.parseInt(h);
if(m>=60)
{
System.out.println(“First division”);
}
else
{
if(m>=45)
{
System.out.println(“Second division”);
}
else
{
System.out.println(“Third division”);
}
}
}
}
The control will goto else section, if the value of variable m<60. In the else section, another set of if else statement is used to check whether m>=45 or not
import java.io.*;
class LogicalOperators
{
public static void main(String args[] )
throws IOException
{
BufferedReader k=new BufferedReader(new InputStreamReader
(System.in));
String h;
int m;
System.out.print(“Enter marks :”);
h=k.readLine( );
m=Integer.parseInt(h);
if(m>=60)
{
System.out.println(“First division”);
}
if(m>=45 && m <60)
{
System.out.println(“Second division”);
}
if(m <45)
{
System.out.println(“Third division”);
}
}
}
Note: As we can see in above example, when we use logical operators, else section can be ignored.
/* Enter two values a and b and print the larger of the two */
import java.io.*;
class LargerNumber
{
public static void main(String args[] )
throws IOException
{
BufferedReader k=new BufferedReader(new InputStreamReader
(System.in));
String h;
int a,b;
System.out.print(“Enter two values :”);
h=k.readLine( );
a=Integer.parseInt(h);
h=k.readLine( );
b=Integer.parseInt(h);
if(a>=b)
{
System.out.println(“Larger is “+a);
}
else
{
System.out.println(“Larger is “+b);
}
}
}
Java If Statement | Java Example
This statement helps in choosing one set of statement out of two sets depending on the validity of the logical expression included. It is also known as conditional branch statement as it is used to route program execution through two different paths.
Syntax:
if (logical expression)
statement(s);
else
statement(s);
If the expression in the parentheses evaluates to true, then if section is executed and if the expression evaluates to false, then else section is executed. Else section is optional.
/* Enter marks and print first div if marks >=60 otherwise print second division. */
import java.io.*;
class IfCondition
{
public static void main(String[] args)
throws IOException
{
BufferedReader k=new BufferedReader(new InputStreamReader
(System.in));
String h;
int m;
System.out.print(“Enter marks : “);
h=k.readLine();
m=Integer.parseInt(h);
if(m>=60)
{
System.out.println(“First Division”);
}
else
{
System.out.println(“Second Division”);
}
}
}
User is asked to enter a value which is stored into an integer variable m. If the value entered in m is greater then or equal to 60, control will execute if section displaying “First Division” on the screen and in case the value in variable m is less then 60, control will execute else section.
Java console io Example
Java.io.Console class is a new class in Java 6 that may be used for reading text from character based console device. The data can be read from the console device provided it is associated with the Java Virtual Machine (JVM).
To determine whether console device is present in the current JVM, we invoke Console() method of System class and if this method returns a Console reference, that means the console device is present in current JVM as shown in following code:
If console device is present in current JVM, we get a console reference which can be used to call the Console class’s methods.
Here is the Java Example for Console I/O:
import java.io.*;
public class ConsoleIO
{
public static void main(String[] args)
{
int p,q,r;
float a;
String val;
Console console=System.console();
val=console.readLine("Enter first value ");
p=Integer.parseInt(val);
val=console.readLine("enter second value ");
q=Integer.parseInt(val);
val=console.readLine("Enter third value ");
r=Integer.parseInt(val);
a=(float)(p+q+r)/3;
System.out.println("Average of three variables is "+a);
}
}
Java.io.Reader.read() Method Example
The java.io package contains stream classes that support for reading and writing. To use these stream classes, we import the java.io package. For reading characters, we prefer Reader class and we use subclass BufferedReader to read data.
The System class in the language package represents the keyboard, or standard input stream. This member variable in system class is called in and that are the instance of the InputStream class. These variable are useful for reading from the keyboard. The System.in object is used to read user input from the keyboard. For reading data, read()/readLine() method is called. Then, by using Integer.parseInt() method, the data is converted from string to integer.
Here is the Java Example for the program Java.io.Reader.read() Method :
import java.io.*;
class AreaofRectangle
{
public static void main (String args[])
throws IOException
{
BufferedReader k=new BufferedReader(new inputStreamReader
(System.in));
String h;
int l,b,a;
System.out.println(“Enter lenght “);
h=k.readLine();
l=Integer.parseInt(h);
a=l*b;
System.out.println(“Area of Rectangle is “+a);
}
}
One Another Java Example we can See.
import java.io.*;
class AverageofThreeVariables
{
public static void main (String args[] )
throws IOException
{
BufferedReader k=new BufferedReader(new InputStreamReader
(System.in));
String h;
int p,q,r;
float a;
System.out.print1n(“Enter first value “);
h=k.raedLine( );
p=Integer.parseInt(h);
System.out.print1n(“Enter second value “);
h=k.raedLine( );
q=Integer.parseInt(h);
System.out.print1n(“enter third value “);
h=k.raedLine( );
r=Integer.parseInt(h);
a=(float)(p+q+r)/3;
System.out.print1n(“Average of three variables is “+a);
}
}
Transpose of a Matrix in Java Example
Algorithm for Transpose of a Matrix:
step 1: read r, c
step 2: create an integer array a[][] of size r,c
step 3: create an integer array b[][] of size c,r
step 4: initialize i=0
step 5: repeat through step-10 while (i < r)
step 6: initialize j=0
step 7: repeat through step-9 while (j < c)
step 8: read a[i][j]
step 9: j=j+ 1
step 10: i=i+ 1
step 11: reset i=0
step 12: repeat through step-17 while (i < r)
step 13: reset j=0
step 14: repeat through step-16 while (j < c)
step 15: b[j][i]=a[i][j]
step 16: j=j+ 1
step 17: i=i+ 1
step 18: initialize i=0
step 19: repeat through step-25 while (i < c)
step 20: move to new line
step 21: initialize j=0
step 22: repeat through step-24 while (j < r)
step 23: print b[i][j]
step 24: j=j+ 1
step 25: i=i+ 1
step 26: Exit
Here is the Java Example for Transpose of a Matrix:
import java.util.Scanner;
class TransposeMatrix
{
public static void main(String args[])
{
int i,j,t,r,c ;
Scanner s1=new Scanner(System.in);
System.out.print("Enter the size of Rows : ");
r=s1.nextInt();
System.out.println("Enter the size of Columns :");
c=s1.nextInt();
System.out.println("\nThe Elements into the Array:->");
int a[][]=new int[r];
int b[][]=new int[r];
for(i=0;i<r;i++)
for(j=0;j<c;j++)
a[i][j]=s1.nextInt();
System.out.println("\nThe elements of Array\n");
for(i=0;i<r;i++)
{
System.out.print("\n");
for(j=0;j<c;j++)
{
System.out.print(a[i][j]+"\t");
}
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
b[j][i]=a[i][j];
}
}
System.out.println("\nAfter Transfering print the data :->");
for(i=0;i<c;i++)
{
System.out.print("\n");
for(j=0;j<r;j++)
{
System.out.print(b[i][j]+"\t");
}
}
}
}
}
Swap Elements of an Array in Java Example
Algorithm for Swap Elements of an Array:
step 1: read y
step 2: create two integer arrays a[],b[] of size y
step 3: initialize x=0
step 4: repeat through step-6 while (x < a.length)
step 5; read b[x]
step 6: x=x+l
step 7: reset x=0
step 8: repeat through step-11 while (x < a.length)
step 9: print a[x]
step 10: print one space
step 11: x=x+l
step 12: Reset x=0
step 13: repeat through step-15 while (x< y)
step 14: interchange a[x],b[x]
step 15: x=x+1
step 16: Exit
Here is the Java Example for Swap Elements of an Array:
import java.util.Scanner;
public class SwapArray
{
public static void main(String args[])
{
int x,y;
Scanner s1=new Scanner(System.in);
System.out.print("Enter the Size of Array : ");
y=s1.nextInt();
int a[]=new int[y];
int b[]=new int[y];
System.out.println("\nEnter The Elements In First Array\n");
for(x=0;x<a.length;x++)
a[x]=s1.nextInt();
System.out.println("\nEnter The Elements In Second Array\n");
for(x=0;x<b.length;x++)
b[x]=s1.nextInt();
System.out.print("The Elements of First Array : ");
for(x=0;x<a.length;x++)
{
System.out.print(a[x]+" ");
}
System.out.print("\nThe Elements of second Array : ");
for(x=0;x<b.length;x++)
{
System.out.print(b[x]+" ");
}
System.out.print("\n");
for(x=0;x<y;x++)
{
a[x]=a[x]+b[x];
b[x]=a[x]-b[x];
a[x]=a[x]-b[x];
}
System.out.println("\nAfter swaping the Output is \n");
System.out.print("The Elements of First Array : ");
for(x=0;x<a.length;x++)
{
System.out.print(a[x]+" ");
}
System.out.print("\nThe Elements of second Array : ");
for(x=0;x<b.length;x++)
{
System.out.print(b[x]+" ");
}
System.out.print("\n");
}
}