JAVA BASIC PROGRAMS
1) SWAPPING TWO NUMBERS
public class
SwappingNumber {
public static void main(String args[]){
System.out.println("Swapping two numbers with third variable");
int a = 45, b = 89;
int temp = a;
a = b;
b = temp;
System.out.println("a value is:"+a);
System.out.println("b value is:"+b);
System.out.println("Swapping two numbers without third variable");
int x = 75, y = 67;
x = x*y;
y = x/y;
x = x/y;
System.out.println("X Value is:"+x+" and Y value is:"+y);
}
}
OUTPUT
Swapping two numbers with third variable
a value is:89
b value is:45
Swapping two numbers without third variable
X Value is:67 and Y value is:75
2) SUM OF DIGITS OF A GIVEN NUMBER
public class
SumOfDigitsOfNumber {
public static void main(String args[]) {
int num = 11341, sum = 0, reminder;
while(num >0){
reminder = num % 10;
sum = sum + reminder;
num = num /10;
}
System.out.println("Sum of digits of a number is: "+sum);
}
}
OUTPUT:-
Sum of digits of a number is: 10
3) REVERSING A STRING
public class
StringReverse {
public static void main(String args[]){
String nameString = "KUMAR GAURAV";
byte[] nameStrArr = nameString.getBytes();
byte[] finalArr = new byte[nameStrArr.length];
for(int i=0; i<nameStrArr.length; i++){
finalArr[i] = nameStrArr[nameStrArr.length - i -1];
}
System.out.println("Reversed String is:"+new String(finalArr));
}
}
OUTPUT
Reversed String is:VARUAG RAMUK
4) IDENTIFYING A ARMSTRONG NUMBER
public class ArmstrongNumber
{
public static void main(String args[]){
int reminder = 0, sum = 0, num = 407, temp ;
temp = num;
while(num > 0){
reminder = num % 10;
sum = sum + (reminder*reminder*reminder);
num = num /10;
}
if(sum == temp){
System.out.println("Given number is Armstrong number");
}else{
System.out.println("Given number is not a Armstrong number");
}
}
}
OUTPUT
Given number is Armstrong number
5) EXECUTION PRIORITY IN JAVA
public class BlocksExecutionPriority
{
static{
System.out.println("I am static block");
}
{
System.out.println("I am not static block");
}
public static void main(String args[]){
System.out.println("I am main method");
BlocksExecutionPriority
bep = new BlocksExecutionPriority();
bep.nonStaticTest();
BlocksExecutionPriority.staticTest();
}
private static void staticTest(){
System.out.println("I am static method");
}
private void
nonStaticTest(){
System.out.println("I am non static method");
}
}
OUTPUT
I am static block
I am main method
I am not static block
I am non static method
I am static method
6) BUBBLE SORT IN JAVA
public class
BubbleSortingInJava {
public static void bubbleSort(int[] numArr){
int n = numArr.length, temp = 0;
for(int i=0; i<n;i++){
for(int j=1; j<(n-i); j++){
if(numArr[j-1]>numArr[j]){
temp = numArr[j-1];
numArr[j-1] = numArr[j];
numArr[j] = temp;
}
}
}
}
public static void main(String args[]){
int[] numArr = {40, 5, 39, 3, 107, 78, 9};
for(int i=0; i<numArr.length; i++){
System.out.println("Number Array before sorting:"+numArr[i]);
}
System.out.println("#####################################");
bubbleSort(numArr);
for(int i=0; i<numArr.length; i++){
System.out.println("Number Array After sorting:"+numArr[i]);
}
}
}
OUTPUT
Number Array before sorting:40
Number Array before sorting:5
Number Array before sorting:39
Number Array before sorting:3
Number Array before sorting:107
Number Array before sorting:78
Number Array before sorting:9
#####################################
Number Array After sorting:3
Number Array After sorting:5
Number Array After sorting:9
Number Array After sorting:39
Number Array After sorting:40
Number Array After sorting:78
Number Array After sorting:107
7) CHECK WHETHER THE GIVEN NUMBER IS PALINDROME OR NOT
public class
CheckPalindromeNumber {
public static void main(String args[]){
int reminder, sum=0, temp, num=686;
temp = num;
while(num>0){
reminder = num % 10;
sum = (sum * 10) + reminder;
num = num /10;
}
if(sum == temp){
System.out.println("Given number is a plindrome number");
}else{
System.out.println("Given number is not a plindrome number");
}
}
}
OUTPUT
Given number is a plindrome number
8) CHECK GIVEN NUMBER IS PALINDROME
public class
CheckPalindromeString {
public static void main(String args[]){
String inputString = "MADAM";
byte[] inputStrArr = inputString.getBytes();
byte[] reverseArr = new byte[inputStrArr.length];
for(int i=0; i<inputStrArr.length; i++){
reverseArr[i] = inputStrArr[inputStrArr.length -i-1];
}
String reversedString = new String(reverseArr);
System.out.println("reversedString is:"+reversedString);
if(inputString.equals(reversedString)){
System.out.println("Given String is a plaindrome");
}else{
System.out.println("Given String is not a plaindrome");
}
}
}
OUTPUT
reversedString is:MADAM
Given String is a plaindrome
9) FIND THE FACTORIAL OF A NUMBER
public class
FactorialNumber {
public static void main(String args[]){
int num=6, fact =1;
for(int i=1; i<=num; i++){
fact = fact * i;
}
System.out.println("Factorial numer is:-"+fact);
}
}
OUTPUT
Factorial numer is:-720
10) FIND THE FIBONACCI NUMBER WITHIN A NUMBER
public class
FibonacciSeries {
public static void main(String args[]){
int a=0, b=1, c;
c=a+b;
System.out.println("Series data are:-"+a);
System.out.println("Series data are:-"+b);
System.out.println("Series data are:-"+c);
while(c<100){
a = b;
b = c;
c = a + b;
System.out.println("Series data are:-"+c);
}
}
}
OUTPUT
Series data are:-0
Series data are:-1
Series data are:-1
Series data are:-2
Series data are:-3
Series data are:-5
Series data are:-8
Series data are:-13
Series data are:-21
Series data are:-34
Series data are:-55
Series data are:-89
Series data are:-144
11) FIND THE GIVEN NUMBER IS PRIME OR NOT
public class PrimeNumber
{
public static void main(String args[]){
for(int i = 0; i<100; i++){
boolean flag = true;
for(int j=2; j<i-1; j++){
if(i%j == 0){
flag = false;
break;
}
}
if(flag == true){
System.out.println("Prime number:-"+i);
}
}
}
}
OUTPUT
Prime number:-0
Prime number:-1
Prime number:-2
Prime number:-3
Prime number:-5
Prime number:-7
Prime number:-11
Prime number:-13
Prime number:-17
Prime number:-19
Prime number:-23
Prime number:-29
Prime number:-31
Prime number:-37
Prime number:-41
Prime number:-43
Prime number:-47
Prime number:-53
Prime number:-59
Prime number:-61
Prime number:-67
Prime number:-71
Prime number:-73
Prime number:-79
Prime number:-83
Prime number:-89
Prime number:-97
12) REVERSE A GIVEN NUMBER
public class
ReverseANumber {
public static void main(String args[]){
int num = 134678, sum = 0, reminder;
while(num >0 ){
reminder = num % 10;
sum = (sum * 10) + reminder;
num = num /10;
}
System.out.println("REVERSED
NUMBER IS:"+sum);
}
}
OUTPUT
REVERSED NUMBER IS:876431
13) SORT A MAP BY KEYS
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class
SortAMAPByKey {
public static void main(String args[]) {
Map<String,
Integer> unsortedMap = new
HashMap<String, Integer>();
unsortedMap.put("D",
5600);
unsortedMap.put("B",
9876);
unsortedMap.put("X",
3456);
unsortedMap.put("N",
1103);
unsortedMap.put("A",
876543);
Map<String,
Integer> sortedMap = new
TreeMap<String, Integer>(unsortedMap);
for(Map.Entry<String, Integer> entry:sortedMap.entrySet()){
System.out.println("Keys are:"+entry.getKey()+"
Value are:-"+entry.getValue());
}
}
}
OUTPUT
Keys are:A Value are:-876543
Keys are:B Value are:-9876
Keys are:D Value are:-5600
Keys are:N Value are:-1103
Keys are:X Value are:-3456
14) SORT A MAP BY VALUES
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class SortAMAPByValue
{
public static void main(String args[]) {
Map<String,
Integer> unsortedMap = new
HashMap<String, Integer>();
unsortedMap.put("D",
5600);
unsortedMap.put("B",
9876);
unsortedMap.put("X",
3456);
unsortedMap.put("N",
1103);
unsortedMap.put("A",
876543);
Set<Entry<String,
Integer>> set = unsortedMap.entrySet();
List<Entry<String,
Integer>> list = new
ArrayList<Entry<String, Integer>>(set);
Collections.sort( list, new
Comparator<Map.Entry<String, Integer>>(){
public int
compare(Map.Entry<String, Integer> object1,
Map.Entry<String, Integer> object2){
return (object2.getValue()).compareTo(object1.getValue());
}
});
for(Map.Entry<String, Integer> entry: list){
System.out.println(entry.getKey() +":" +entry.getValue());
}
}
}
OUTPUT
A:876543
B:9876
D:5600
X:3456
N:1103
15) RETURN VALUE FROM FINALLY BLOCK AFTER EXCEPTION IS THROWN FROM TRY BLOCK.
public class
TestFinallyReturn {
public static void main(String args[]){
String test = "finallyReturn";
System.out.println("Checking the value:-"+testFinally(test));
}
private static
String testFinally(String value) {
String check = null;
try{
check.toString();
}catch(Exception e){
e.printStackTrace();
}finally{
return value;
}
}
}
OUTPUT
java.lang.NullPointerException
at
com.gaurav.interfacetest.TestFinallyReturn.testFinally(TestFinallyReturn.java:14)
at
com.gaurav.interfacetest.TestFinallyReturn.main(TestFinallyReturn.java:7)
Checking the value:-finallyReturn
16) Removing duplicate elements from an unsorted array
import java.util.Arrays;
public class RemoveDuplicatesOfAnArray {
static int removeDuplicates(int arr[], int length) {
if (length == 0
|| length == 1) {
return length;
}
int j = 0;
int[] temp = new int[length];
for (int i = 0; i < length - 1; i++) {
if (arr[i] != arr[i + 1]) {
temp[j++] = arr[i];
}
}
temp[j++] = arr[length - 1];
for (int i = 0; i < j; i++) {
arr[i] = temp[i];
}
return j;
}
public static void main(String args[]) {
int arr[] = {
60, 70, 30, 10, 10, 20, 20, 30, 30, 40, 50, 50 };
Arrays.sort(arr);
int length = arr.length;
length = removeDuplicates(arr, length);
for (int i = 0; i < length; i++)
System.out.print(arr[i]+"\t");
}
}
OUTPUT
10 20 30 40 50 60 70
17) Removing
duplicate elements from an unsorted String array
port java.util.Arrays;
import java.util.HashSet;
public class RemoveDuplicatesFromStringArray {
public static void main(String args[]) {
String arr[] = { "gaurav", "Ram", "Aaditya", "Anurag", "gaurav", "Suresh", "Manoj", "Aaditya", "Aaditya" };
arr = new HashSet<String>(Arrays.asList(arr)).toArray(new String[0]);
Arrays.sort(arr);
String newArr[] = new String[arr.length];
System.out.println("String names array after removing duplicates
array length is:-" + arr.length);
for (int i = 0; i < arr.length; i++) {
newArr[i] = arr[i];
System.out.println("Elements are:-" + newArr[i]);
}
}
}
OUTPUT
String
names array after removing duplicates array length is:-6
Elements
are: -Aaditya
Elements
are: -Anurag
Elements
are: -Manoj
Elements
are: -Ram
Elements
are: -Suresh
Elements
are: -gaurav
18) Swapping String without using Third Variable
public class SwappingStringWithoutThirdVariable {
public static void main(String[] args) {
String firstName = "Kumar";
String secondName = "Gaurav";
firstName = firstName + secondName;
secondName = firstName.substring(0,
firstName.length() - secondName.length());
firstName = firstName.substring(secondName.length());
System.out.println("FirstName is:-"+firstName +" & secondName is:"+secondName);
}
}
OUTPUT
FirstName
is: -Gaurav & secondName is: Kumar
19) Lambda Expression Example
public class LambdaExpressionExample {
public static void main(String[] args) {
//Without Lambda Expression
lambdaDemo demo = new lambdaDemo(){
@Override
public void printMyNameAndDoAddition(String name, int x, int y) {
System.out.println("My Name is:-"+name);
int sum = x + y;
System.out.println("Addition of given number is:"+sum);
};
};
demo.printMyNameAndDoAddition("Gaurav", 100, 500); //for traditional way of execution
//Using Lambda Expression
lambdaDemo demo1 =(name1, x, y)-> {
int sum = x +y;
System.out.println("My Name is:-"+name1);
System.out.println("Addition of number under Lambda expression
implementation is:-"+sum);
};
demo1.printMyNameAndDoAddition("Kumar", 6500, 9500);// Using Lambda Expression execution.
}
}
@FunctionalInterface
interface lambdaDemo{
void printMyNameAndDoAddition(String name, int x, int y);
}
OUTPUT
My
Name is:-Gaurav
Addition
of given number is:600
My
Name is:-Kumar
Addition
of number under Lambda expression implementation is:-16000
20) Find Common Elements in Two Integer Array
public class FindCommonInTwoArray {
public static void main(String args[]){
int firstArr[] =
{15,7,6,8,9,11,14};
int secondArr[] =
{7, 11, 80,65,9,101,8};
for(int i = 0; i< firstArr.length; i++){
for(int j=0; j< secondArr.length; j++){
if(firstArr[i] == secondArr[j]){
System.out.println("Common Elements are:"+firstArr[i]);
}
}
}
}
}
OUTPUT
Common
Elements are:7
Common
Elements are:8
Common
Elements are:9
Common
Elements are:11
21) Find Common Elements in Two String Array
import java.util.HashSet;
public class FindCommonInStringArray {
public static void main(String args[]){
String nameStringArr1[] = {"Kumar", "Aaditya","Shivam","Gaurav", "Ritika","Mihika"};
String nameStringArr2[] = {"Shivam", "Jiya", "Abhishek", "Gaurav", "Aaditya"};
HashSet<String> hashSet = new HashSet<String>();
for(int i=0; i<nameStringArr1.length; i++){
for(int j=0; j<nameStringArr2.length; j++){
if(nameStringArr1[i].equals(nameStringArr2[j])){
hashSet.add(nameStringArr1[i]);
}
}
}
System.out.println("Common Elements are:-"+hashSet);
}
}
OUTPUT
Common
Elements are:-[Shivam, Gaurav, Aaditya]
22) REVERSING A STRING USING RECURSION
public class ReverseStringUsingRecursion {
static String reverseString(String str){
if(str.length()==
1 || str.isEmpty())
return str;
return reverseString(str.substring(1)) + str.charAt(0);
}
public static void main(String[] args) {
String name = "Gaurav Aaditya";
String reversedName = reverseString(name);
System.out.println("Reversed String is:"+reversedName);
}
}
OUTPUT
Reversed
String is:aytidaA varuaG
23) CHECK TWO STRINGS ARE ANAGRAM OR NOT
import java.util.Arrays;
public class CheckStringsAnagram {
static void isStringAnagram(String str1, String str2) {
//Removing the Spaces in between the given string
String firstString = str1.replaceAll("\\s", "");
String secondString = str2.replaceAll("\\s", "");
boolean anagramStatus = true;
//if both string length is different then retruning
Anagram status as false;
if (firstString.length()
!= secondString.length()) {
anagramStatus = false;
} else {
//Arranging the strings in character array in upper
case
char[] firstStrArr = firstString.toUpperCase().toCharArray();
char[] secondStrArr = secondString.toUpperCase().toCharArray();
//Sorting both the character array to check whether
both the given string are equal to not.
Arrays.sort(firstStrArr);
Arrays.sort(secondStrArr);
anagramStatus = Arrays.equals(firstStrArr, secondStrArr);
}
if (anagramStatus) {
System.out.println("Given String "+firstString + " and " + secondString + " both are anagrams");
} else {
System.out.println("Given String "+firstString + " and " + secondString + " are not anagrams");
}
}
public static void main(String[] args) {
isStringAnagram("act", "cat");
isStringAnagram("Tear", "fear");
isStringAnagram("Mother In Law", "Hitler Woman");
}
}
OUTPUT
Given
String act and cat both are anagrams
Given
String Tear and fear are not anagrams
Given
String MotherInLaw and HitlerWoman both are anagrams
24) PRINT A NUMBER WITHOUT LOOP
public class PrintNumberWithoutLoop {
static void printNumber(int n){
if(n
>0){
printNumber(n - 1);
System.out.println(n+"
");
}
return;
}
public static void main(String args[]){
printNumber(5);
}
}
OUTPUT
1
2
3
4
5
25) FIND SECOND LARGEST NUMBER IN A NUMBER ARRAY
public class SecondLargestInArrayExample {
public static int getSecondLargest(int[] numArr) {
int temp;
for (int i = 0; i < numArr.length; i++) {
for (int j = i + 1; j < numArr.length; j++) {
if (numArr[i] > numArr[j]) {
temp = numArr[i];
numArr[i] = numArr[j];
numArr[j] = temp;
}
}
}
return numArr[numArr.length - 2];
}
public static void main(String args[]) {
int numArr[] = {
144, 355, 89, 876, 991, 59, 15 };
System.out.println("Second Largest: " + getSecondLargest(numArr));
}
}
OUTPUT
Second
Largest: 876
It is really very helpful.
ReplyDelete