Sunteți pe pagina 1din 14

https://beginnersbook.

com/category/java-examples/
1)to check Vowel or Consonant using Switch Case
public class CaseConsAndVoc {

public static void main(String[] args) {


boolean isVocal = false;
Scanner scan = new Scanner(System.in);
System.out.println("Enter a character");
char ch = scan.next().charAt(0);
scan.close();
switch(ch)
{
case 'a':
case 'e':
case 'i': isVocal=true;
}
if(isVocal==true)
{
System.out.println("It is vocal");
}
else
{
System.out.println("It is a Consonant");
}
====================================
2)public class breakintegerintodigits {

public static void main(String[] args) {


// TODO Auto-generated method stub
int num = 0,temp,digit,count=0;

//insert number
Scanner scan=new Scanner(System.in);
System.out.println("Insert number");
scan.hasNextInt();
scan.close();

//making a copy of the input number


temp=num;
//counting digits in the input number
while(num>0)
{
num=num/10;
count++;
}
while(temp>0)
{
digit=temp%10;
System.out.println("Digit at place " + count + " is " +
digit);
temp=temp/10;
count--;
}
}
====================================================
3)public class Palendorn {

public static boolean IsPal(String s) {

if (s.charAt(0) == s.charAt(s.length() - 1))


return IsPal(s.substring(1, s.length() - 1));
return false;
}

public static void main(String[] args) {


// TODO Auto-generated method stub
Scanner scan=new Scanner(System.in);
System.out.println("Enter the String for check");
String string = scan.nextLine();

if(IsPal(string))
System.out.println(string+" Is palindrom");
else
System.out.println(string + "Is not palindrom");

}
==============================
4)public class EvenAndOdd {

public static void main(String[] args) {


// TODO Auto-generated method stub
int num;
Scanner scan=new Scanner(System.in);

num=scan.nextInt();

if(num%2==0)
System.out.println(num + "It is a odd numebr");
else
System.out.println(num + "It is a n even
number");

}
============================================
5)How To Convert Char To String and a String to char in Java
class CharToStringDemo
public class StringToArray {

public static void main(String[] args) {


// Convert Char To String
char[] ch = { 'g', 'o', 'o', 'd', ' ', 'm', 'o', 'r', 'n', 'i',
'n', 'g' };
String str = new String(ch);
System.out.println("String is : " + str);

String str4 = String.valueOf(ch);


System.out.println(str);
////////////////////
char ch2 = 'a';
String str2 = String.valueOf(ch2);
System.out.println("String is :" + str2);

String str3 = "Hello";


for (int i = 0; i < str3.length(); i++) {
char ch3 = str3.charAt(i);
System.out.println("Character at " + i + "Position : " +
ch3);
}
==================
6)count vowels and consonants in a given String
public static void main(String[] args) {
// TODO Auto-generated method stub
String str="BegenniersBook";
int vcount = 0,ccount=0;
str=str.toLowerCase();
for(int i=0;i<str.length();i++)
{
char ch=str.charAt(i);
if(ch=='a'|| ch == 'e' || ch == 'i' || ch == 'o' || ch
== 'u')
{
vcount++;
}
else
{
ccount++;
}

}
System.out.println("Numbers of Vowels: " + vcount);
System.out.println("Number of Consonants " + ccount);
}

============================
8)reverse words in a String
import java.util.Scanner;

public class reversewordsinaString {

public static void main(String[] args) {


String str;
System.out.println("Enter your username: ");
Scanner scanner = new Scanner(System.in);
str = scanner.nextLine();
scanner.close();
String reversed = reverseString(str);
System.out.println("The reversed string is: " + reversed);
}

public static String reverseString(String str)


{
if (str.isEmpty())
return str;
//Calling Function Recursively
return reverseString(str.substring(1)) + str.charAt(0);
}
}
==============================
9)generate random numbers
public class RundomNumbers {

public static void main(String[] args) {


// /* Below code would generate 5 random numbers
// * between 0 and 200.
// */
int counter;
Random rnum=new Random();

System.out.println("Random no : ");
for(int i=0;i<5;i++)
System.out.println(rnum.nextInt(200));
}
==============================
10) print alternate prime numbers
public class PrimeNumbers {

public static void main(String[] args) {


// TODO Auto-generated method stub
int num=20;
System.out.println("Alternate prime number up to " + num +
"are");
printAltPrime(num);
}

static int checkPrime(int num)


{
int i,flag=0;
for(i=2;i<=num/2;i++)
{
if(num%i==0)
{
flag=1;
break;
}
}
/* If flag value is 0 then the given number num
* is a prime number else it is not a prime number
*/
if(flag==0)
return 1;
else
return 0;
}
//Method for printing alternate prime numbers
static void printAltPrime(int n)
{
int temp=2;
for(int num=2;num<=n-1;num++)
{
if(checkPrime(num)==1)
{
if(temp%2==0)
System.out.println(num + "");
temp++;
}
}
}
}
=================================
11)Display Fibonacci Series using loops
The Fibonacci sequence is a series of numbers where a number is the sum of
previous two numbers. Starting with 0 and 1, the sequence goes
0, 1, 1, 2, 3, 5, 8, 13, 21, and so on. Here we will write three programs
to print fibonacci series 1) using for loop 2) using while loop
3) based on the number entered by user
import java.util.Scanner;

public class Fibonacci {

public static void main(String[] args) {


// TODO Auto-generated method stub
int count,num1=0,num2=1;
System.out.println("How many numbers do you want in sequence");
Scanner scan=new Scanner(System.in);
count=scan.nextInt();
scan.close();
System.out.println("I got " + count+ "numbers");

// int i=1;
// while(i<=count)
// {
// System.out.println(num1 + "");
// int sumPrev=num1+num2;
// num1=num2;
// num2=sumPrev;
// i++;
// }
System.out.println("another aproach");
for(int i1=1;i1<=count;i1++)
{
System.out.println(num1 + " ");
int sumPrev=num1+num2;
num1=num2;
num2=sumPrev;
}
}

12)Find Factorial using For and While loop


We will write three java programs to find factorial of a number.
1) using for loop 2) using while loop 3) finding factorial of a number
entered by user. Before going through the program, lets understand what
is factorial: Factorial of a number n is denoted as n! and the value of
n! is: 1 * 2 * 3 * … (n-1) * n
public class Factorial {

public static void main(String[] args) {


// TODO Auto-generated method stub
int num = 5;
long fact = 1;
for (int i = 1; i <= num; i++) {
fact = fact * i;
}
System.out.println("Factorial of " + num + "it is :" + fact);

System.out.println("Another way using while");


int i = 1;
while (i <=num) {
fact = fact * i;
i++;
}
System.out.println("Factorial of " + num + "it is :" + fact);
}

}
13)reverse the Array
public class array {

public static void main(String[] args) {


// TODO Auto-generated method stub
int aiFirtsArray[]=new int[6];
for(int i=0;i<aiFirtsArray.length;i++)
{
aiFirtsArray[i]=i+1;
}
for(int i=0;i<aiFirtsArray.length;i++)
{
System.out.println(aiFirtsArray[i]);
}

=========
public class reversetheArray {

public static void main(String[] args) {


int counter, i = 0, j = 0, temp;
int number[] = new int[100];
Scanner scanner = new Scanner(System.in);
System.out.print("How many elements you want to enter: ");
counter = scanner.nextInt();

/*
* This loop stores all the elements that we enter in an the
array number. First
* element is at number[0], second at number[1] and so on
*/
for (i = 0; i < counter; i++) {
System.out.print("Enter Array Element" + (i + 1) + ":
");
number[i] = scanner.nextInt();
}

/*
* Here we are writing the logic to swap first element with last
element, second
* last element with second element and so on. On the first
iteration of while
* loop i is the index of first element and j is the index of
last. On the
* second iteration i is the index of second and j is the index
of second last.
*/
j = i - 1;
i = 0;
scanner.close();
while (i < j) {
temp = number[i];
number[i] = number[j];
number[j] = temp;
i++;
j--;
}

System.out.print("Reversed array: ");


for (i = 0; i < counter; i++) {
System.out.print(number[i] + " ");
}
}
============
14)find the largest number using ternary operator
result = num3 > (num1>num2 ? num1:num2) ? num3:((num1>num2) ? num1:num2);
public class LArgerstNumOfThree {

public static void main(String[] args) {


// TODO Auto-generated method stub

int num1,num2,num3,result,temp;
/* Scanner is used for getting user input.
* The nextInt() method of scanner reads the
* integer entered by user.
*/
Scanner scanner = new Scanner(System.in);
System.out.println("Enter First Number:");
num1 = scanner.nextInt();
System.out.println("Enter Second Number:");
num2 = scanner.nextInt();
System.out.println("Enter Third Number:");
num3 = scanner.nextInt();
scanner.close();
temp=num1>num2?num1:num2;
result=num3>temp?num3:temp;
System.out.println("LArgest number is " + result);
}
=============
15)
class SortByteArray {

public static void main(String[] args) {

// Creating a Byte Array


byte[] byteArray = new byte[] { 13, 9, 15, 24, 4 };

// Displaying Array before Sorting


System.out.println("**byte Array Before Sorting**");
for (byte temp: byteArray){
System.out.println(temp);
}

// Sorting the Array


Arrays.sort(byteArray);
System.out.println("**byte Array After Sorting**");
for (byte temp: byteArray){
System.out.println(temp);
}

// Another byte Array


byte[] byteArray2 =
new byte[] { 15, 22, 3, 41, 24, 77, 8, 9 };

// Selective Sorting
/* public static void sort(byte[] a, int fromIndex,
* int toIndex): Sorts the specified range of the
* array into ascending order. The range to be sorted
* extends from the index fromIndex, inclusive, to the
* index toIndex, exclusive. If fromIndex == toIndex,
* the range to be sorted is empty.
*/
Arrays.sort(byteArray2, 2, 5);

// Displaying array after selective sorting


System.out.println("**Selective Sorting**");
for (byte temp: byteArray2){
System.out.println(temp);
}
}
}
=================================
16)String sort
int count;
String temp;
Scanner scan = new Scanner(System.in);

//User will be asked to enter the count of strings


System.out.print("Enter number of strings you would like to enter:");
count = scan.nextInt();

String str[] = new String[count];


Scanner scan2 = new Scanner(System.in);

//User is entering the strings and they are stored in an array


System.out.println("Enter the Strings one by one:");
for(int i = 0; i < count; i++)
{
str[i] = scan2.nextLine();
}
scan.close();
scan2.close();

//Sorting the strings


for (int i = 0; i < count; i++)
{
for (int j = i + 1; j < count; j++) {
if (str[i].compareTo(str[j])>0)
{
temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
}

//Displaying the strings after sorting them based on alphabetical order


System.out.print("Strings in Sorted Order:");
for (int i = 0; i <= count - 1; i++)
{
System.out.print(str[i] + ", ");
}
}
}
===================
17)ReverseANumber
int num=0;
int reversenum =0;
System.out.println("Input your number and press enter: ");
//This statement will capture the user input
Scanner in = new Scanner(System.in);
//Captured input would be stored in number num
num = in.nextInt();
//While Loop: Logic to find out the reverse number
while( num != 0 )
{
reversenum = reversenum * 10;
reversenum = reversenum + num%10;
num = num/10;
}

System.out.println("Reverse of input number is: "+reversenum);


}
}
====================
class ForLoopReverseDemo
{
public static void main(String args[])
{
int num=0;
int reversenum =0;
System.out.println("Input your number and press enter: ");
//This statement will capture the user input
Scanner in = new Scanner(System.in);
//Captured input would be stored in number num
num = in.nextInt();
/* for loop: No initialization part as num is already
* initialized and no increment/decrement part as logic
* num = num/10 already decrements the value of num
*/
for( ;num != 0; )
{
reversenum = reversenum * 10;
reversenum = reversenum + num%10;
num = num/10;
}

System.out.println("Reverse of specified number is: "+reversenum);


}
}
==============================================
Reverse a number using recursion
import java.util.Scanner;
class RecursionReverseDemo
{
//A method for reverse
public static void reverseMethod(int number) {
if (number < 10) {
System.out.println(number);
return;
}
else {
System.out.print(number % 10);
//Method is calling itself: recursion
reverseMethod(number/10);
}
}
public static void main(String args[])
{
int num=0;
System.out.println("Input your number and press enter: ");
Scanner in = new Scanner(System.in);
num = in.nextInt();
System.out.print("Reverse of the input number is:");
reverseMethod(num);
System.out.println();
}
==============================
18)BoobleSort

class BubbleSortExample {
public static void main(String []args) {
int num, i, j, temp;
Scanner input = new Scanner(System.in);

System.out.println("Enter the number of integers to sort:");


num = input.nextInt();

int array[] = new int[num];

System.out.println("Enter " + num + " integers: ");

for (i = 0; i < num; i++)


array[i] = input.nextInt();

for (i = 0; i < ( num - 1 ); i++) {


for (j = 0; j < num - i - 1; j++) {
if (array[j] > array[j+1])
{
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
System.out.println("Sorted list of integers:");

for (i = 0; i < num; i++)


System.out.println(array[i]);
}
=====================================

19)Linear Search
* Program: Linear Search Example
* Written by: Chaitanya from beginnersbook.com
* Input: Number of elements, element's values, value to be searched
* Output:Position of the number input by user among other numbers*/
import java.util.Scanner;
class LinearSearchExample
{
public static void main(String args[])
{
int counter, num, item, array[];
//To capture user input
Scanner input = new Scanner(System.in);
System.out.println("Enter number of elements:");
num = input.nextInt();
//Creating array to store the all the numbers
array = new int[num];
System.out.println("Enter " + num + " integers");
//Loop to store each numbers in array
for (counter = 0; counter < num; counter++)
array[counter] = input.nextInt();

System.out.println("Enter the search value:");


item = input.nextInt();

for (counter = 0; counter < num; counter++)


{
if (array[counter] == item)
{
System.out.println(item+" is present at location "+(counter+1));
/*Item is found so to stop the search and to come out of the
* loop use break statement.*/
break;
}
}
if (counter == num)
System.out.println(item + " doesn't exist in array.");
}
}
=======================
20)BoobleSearchOnString
ublic class JavaExample {
public static void main(String []args) {
String str[] = { "Ajeet", "Steve", "Rick", "Becky", "Mohan"};
String temp;
System.out.println("Strings in sorted order:");
for (int j = 0; j < str.length; j++) {
for (int i = j + 1; i < str.length; i++) {
// comparing adjacent strings
if (str[i].compareTo(str[j]) < 0) {
temp = str[j];
str[j] = str[i];
str[i] = temp;
}
}
System.out.println(str[j]);
}
}
}=========================
21)Duplicate in string
public class Details {

public void countDupChars(String str){

//Create a HashMap
Map<Character, Integer> map = new HashMap<Character, Integer>();

//Convert the String to char array


char[] chars = str.toCharArray();

/* logic: char are inserted as keys and their count


* as values. If map contains the char already then
* increase the value by 1
*/
for(Character ch:chars){
if(map.containsKey(ch)){
map.put(ch, map.get(ch)+1);
} else {
map.put(ch, 1);
}
}

//Obtaining set of keys


Set<Character> keys = map.keySet();

/* Display count of chars if it is


* greater than 1. All duplicate chars would be
* having value greater than 1.
*/
for(Character ch:keys){
if(map.get(ch) > 1){
System.out.println("Char "+ch+" "+map.get(ch));
}
}
}

public static void main(String a[]){


Details obj = new Details();
System.out.println("String: BeginnersBook.com");
System.out.println("-------------------------");
obj.countDupChars("BeginnersBook.com");

System.out.println("\nString: ChaitanyaSingh");
System.out.println("-------------------------");
obj.countDupChars("ChaitanyaSingh");

System.out.println("\nString: #@$@!#$%!!%@");
System.out.println("-------------------------");
obj.countDupChars("#@$@!#$%!!%@");
}
}
===================
22)FindChString
static void countEachChar(String str)
{
//ASCII values ranges upto 256
int counter[] = new int[256];

//String length
int len = str.length();

/* This array holds the occurrence of each char, For example


* ASCII value of A is 65 so if A is found twice then
* counter[65] would have the value 2, here 65 is the ASCII value
* of A
*/
for (int i = 0; i < len; i++)
counter[str.charAt(i)]++;

// We are creating another array with the size of String


char array[] = new char[str.length()];
for (int i = 0; i < len; i++) {
array[i] = str.charAt(i);
int flag = 0;
for (int j = 0; j <= i; j++) {

/* If a char is found in String then set the flag


* so that we can print the occurrence
*/
if (str.charAt(i) == array[j])
flag++;
}

if (flag == 1)
System.out.println("Occurrence of char " + str.charAt(i)
+ " in the String is:" + counter[str.charAt(i)]);
}
}
public static void main(String[] args)
{
String str = "beginnersbook";
countEachChar(str);
}
}
==============================