Java Examples

package temp;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileReader;

import java.io.FileWriter;

import java.io.IOException;

import java.util.ArrayList;

import java.util.Arrays;

        import java.util.HashMap;

        import java.util.Map;

        import java.util.Properties;

import java.util.Scanner;

import org.json.simple.JSONObject;

import org.json.simple.parser.JSONParser;

import org.json.simple.parser.ParseException;

import org.testng.annotations.Test;

public class javaExamples {

// @Test

public void swapNumbers() {

int a = 10, b = 20;

b = (a + b) - (a = b);

System.out.println(a + "Values" + b);

// using third variable

int i = 10, j = 20, k = 0;

k = i;

i = j;

j = k;

System.out.println(i + " I Value >>" + j + " J Value ");

}

// @Test

public void reverseNumbers() {

int num = 123456;

int rev = 0;

while (num > 0) {

rev = rev * 10 + num % 10;

num = num / 10;

}

System.out.println(rev);

// Second Way

int num1 = 1234;

StringBuilder sb1 = new StringBuilder(String.valueOf(num1));

System.out.println(sb1.reverse());

// Third Way

StringBuffer sb = new StringBuffer(String.valueOf(num1));

System.out.println(sb.reverse());

}

// @Test

public void reverseString() {

String str = "RAVI";

String rev = "";

int len = str.length();

for (int i = len - 1; i > 0; i--) {

rev = rev + str.charAt(i);

}

System.out.println(rev);

// Second Way

StringBuilder sb = new StringBuilder(str);

System.out.println(sb.reverse());

// Third Way

StringBuffer sb1 = new StringBuffer(str);

System.out.println(sb1.reverse());

}

// @Test

public void palindromeNumber() {

int num = 123454321;

int original = num;

int rev = 0;

while (num > 0) {

rev = rev * 10 + num % 10;

num = num / 10;

}

System.out.println(rev);

if (original == rev)

System.out.println("Provided Number is Palindrome Number");

else

System.out.println("Provided Number is NOT a Palindrome Number");

}

// @Test

public void palindromeString() {

String str = "MADAM";

String original = str;

int len = str.length();

String rev = "";

for (int i = len - 1; i >= 0; i--) {

rev = rev + str.charAt(i);

}

System.out.println(rev);

if (original.equals(rev))

System.out.println("Provided String is Palindrome String");

else

System.out.println("Provided String is NOT a Palindrome String");

System.out.println("");

}

// @Test

public void countNumberofDigits() {

int num = 1234534;

int count = 0;

while (num > 0) {

num = num / 10;

count++;

}

System.out.println(count);

}

// @Test

public void sumOfDigits() {

int num = 12345;

int sum = 0;

while (num > 0) {

sum = sum + num % 10;

num = num / 10;

}

System.out.println(sum);

}

// @Test

public void oddEvenNumbers() {

int num = 123456719, temp = 0;

ArrayList<Integer> even = new ArrayList<>();

ArrayList<Integer> odd = new ArrayList<>();

while (num > 0) {

temp = num % 10;

num = num / 10;

if (temp % 2 == 0)

even.add(temp);

else

odd.add(temp);

}

System.out.println(even);

System.out.println(odd);

}

// @Test

public void largetNumber() {

int a = 10, b = 20, c = 30;

int lar1 = (a > b) ? a : b;

int lar2 = (lar1 > c) ? lar1 : c;

System.out.println(lar2);

}

// @Test

public void fibonacciSeries() {

int a = 0, b = 1, temp = 0;

System.out.print(a + " " + b + " ");

for (int i = 0; i < 10; i++) {

temp = a + b;

a = b;

b = temp;

System.out.print(temp + " ");

}

System.out.println("");

}

// @Test

public void printStarsIncrease() {

int num = 5;

for (int i = 1; i <= num; i++) {

for (int j = 0; j < i; j++) {

System.out.print("*");

}

System.out.println();

}

}

// @Test

public void findMaxMinArray() {

int[] array = { 10, 133, 54, 199, 5, 4, 3, 2, 1 };

int max = 0, min = Integer.MAX_VALUE;

for (int value : array) {

if (value > max)

max = value;

if (value < min)

min = value;

}

System.out.println(max);

System.out.println(min);

}

// @Test

public void equalArray() {

int arr1[] = { 2, 3, 5 };

int arr2[] = { 5, 3, 2 };

Arrays.sort(arr1);

Arrays.sort(arr2);

System.out.println(Arrays.toString(arr2));

boolean status = true;

System.out.println(Arrays.toString(arr1));

if (arr1.length == arr2.length) {

for (int i = 0; i < arr1.length; i++)

if (arr1[i] != arr2[i]) {

status = false;

}

} else

status = false;

if (status)

System.out.println("Arrays are equal");

else

System.out.println("Arrays are NOT equal");

// Second Way

status = Arrays.equals(arr1, arr2);

if (status)

System.out.println("Arrays are equal");

else

System.out.println("Arrays are NOT equal");

}

// @Test

public void evenOddArray() {

int[] array = { 12, 4, 6, 7, 9, 3, 5, 3, 4, 1 };

ArrayList<Integer> even = new ArrayList<>();

ArrayList<Integer> odd = new ArrayList<>();

for (int value : array) {

if (value % 2 == 0)

even.add(value);

else

odd.add(value);

}

System.out.println(even);

System.out.println(odd);

}

// @Test

public void sumofArryNumbers() {

int[] num = { 2, 5, 9, 3, 5 };

int sum = 0;

for (int value : num)

sum = sum + value % 10;

System.out.println(sum);

}

// @Test

public void CompareTwoStrings() {

String str = "RAVI", str1 = "Ravi";

int result = str.compareTo(str1);

if (result == 0)

System.out.println("Stings are same");

else

System.out.println("Strings are NOT same");

result = str.compareToIgnoreCase(str1);

if (result == 0)

System.out.println("Stings are same");

else

System.out.println("Strings are NOT same");

}

// @Test

public void splitExample() {

String str = "I am Ravi";

String[] str1 = str.split(" ");

System.out.println(str1[0]);

System.out.println(str1[1]);

System.out.println(str1[2]);

}

// @Test

public void replaceExample() {

String str = "Hello2World2Ravi";

str = str.replace("2", " ");

System.out.println(str);

}

// @Test

public void replaceAll() {

String str = "ldjsfldjf*^*&*^*^*&()*&()";

str = str.replaceAll("[^a-zA-Z0-9]", "");

System.out.println(str); // it will exclude special chars

str = "ldjsfldjf*^*&*^*^*&()*&()";

str = str.replaceAll("[a-zA-Z0-9]", "");

System.out.println(str); // it will display only special chars

}

// @Test

public void avaragetElementsArray() {

double[] num = { 2.15, 4.55, 6.7, 3.22, 5 };

double avg = 0.00;

double sum = 0.0;

for (double value : num) {

sum = sum + value;

}

int len = num.length;

avg = sum / len;

System.out.println(avg);

}

// @Test

public void sortElementsArray() {

int[] num = { 1, 4, 77, 66, 44, 34, 3, 9, 99 };

System.out.println(Arrays.toString(num));

Arrays.sort(num);

System.out.println(Arrays.toString(num));

}

// @Test

public void smallestElementArray() {

int[] num = { 3, 6, 3, 2, 9, 1, 88, 33, 22, 55, 36 };

int smallNum = Integer.MAX_VALUE;

for (int i = 0; i < num.length; i++) {

if (smallNum > num[i]) {

smallNum = num[i];

}

}

System.out.println(smallNum);

}

// @Test

public void largestElementArray() {

int[] num = { 3, 6, 3, 2, 9, 1, 88, 33, 22, 55, 36 };

int largeNum = 0;

int secLargNum = 0;

for (int i = 0; i < num.length; i++) {

if (num[i] > largeNum) {

largeNum = num[i];

}

}

System.out.println(largeNum);

}

// @Test

public void subStringExample() {

String str = "RAVI KRISHNA SAI";

System.out.println(str.substring(9));

System.out.println(str.substring(4, 10));

System.out.println(str.subSequence(3, 10));

System.out.println(str.substring(3, 4));

}

// @Test

public void stringContainsExample() {

String str = "Testing Java";

if (str.contains("Java"))

System.out.println("String Contains the Java");

else

System.out.println("Java string is not there");

}

// @Test

public void trimExample() {

String str = "        testing         ";

str = str.trim();

System.out.println(str);

}

// @Test

public void arrayConvertToString() {

int[] num = { 33, 55, 77, 3, 5, 8, 7, 88 };

System.out.println(Arrays.toString(num));

}

// @Test

public void addNewNumberArray() {

Integer[] num = { 33, 55, 77, 3, 5, 8, 7, 88 };

ArrayList<Integer> newNum = new ArrayList<Integer>(Arrays.asList(num));

newNum.add(1);

System.out.println(newNum);

}

// @Test

public void toLowerCase() {

String str = "TESTING";

str = str.toLowerCase();

System.out.println(str);

}

// @Test

public void toUpperCase() {

String str = "testing";

str = str.toUpperCase();

System.out.println(str);

}

// @Test

public void indexOf() {

String str = "Testing";

int result = str.indexOf('s');

System.out.println(result);

}

// @Test

public void matches() {

String regex = "^J..a$";

boolean str = "Java".matches(regex);

if (str)

System.out.println("String matching");

else

System.out.println("String NOT matching");

}

// @Test

public void startsWith() {

String str = "Java is Best";

boolean result = str.startsWith("Java");

if (result)

System.out.println("String with Java");

else

System.out.println("String NOT with Java");

}

// @Test

public void endsWith() {

String str = "Java is Best";

boolean result = str.endsWith("Best");

if (result)

System.out.println("Ends with Best");

else

System.out.println("Ends NOT with Best");

}

// @Test

public void isEmpty() {

String str = "";

boolean result = str.isEmpty(); // is empty works as length of the String

// is blank works as empty or white space

if (result)

System.out.println("Empty String");

else

System.out.println("NOT Empty String");

}

// @Test

public void joinString() {

String str1 = "I";

String str2 = "love";

String str3 = "Java";

// join strings with space between them

String joinedStr = String.join(" ", str1, str2, str3);

System.out.println(joinedStr);

}

// @Test

public void replaceFirst() {

String str1 = "aabbaaac";

String str2 = "Learn223Java55@";

// regex for sequence of digits

String regex = "\\d+";

// the first occurrence of "aa" is replaced with "zz"

System.out.println(str1.replaceFirst("aa", "zz")); // zzbbaaac

// replace the first sequence of digits with a whitespace

System.out.println(str2.replaceFirst(regex, " ")); // Learn Java55@

}

// @Test

public void createWriteReadFile() throws IOException {

String myFileName = "test.txt";

String write = "url = https://www.google.com/;";

File fi = new File(myFileName);

boolean result = fi.createNewFile();

if (result) {

System.out.println("File is Created");

// Write to the file

FileWriter fw = new FileWriter(myFileName);

fw.write(write);

fw.close();

// Read file

Properties pro = new Properties();

FileInputStream Fis = new FileInputStream(myFileName);

pro.load(Fis);

System.out.println(pro.getProperty("url"));

}

}

// @Test

public void readJSonFileData() throws ParseException, FileNotFoundException, IOException {

JSONParser pars = new JSONParser();

Object obj = pars.parse(new FileReader("temp.json"));

JSONObject jobj = (JSONObject) obj;

String myURL = (String) jobj.get("url");

System.out.println(myURL);

}

// @Test

public void countNumberofLines() throws FileNotFoundException {

File file = new File("test.config");

Scanner sc = new Scanner(file);

int count = 0;

while (sc.hasNextLine()) {

sc.nextLine();

count++;

}

System.out.println("Number of Lines in File >> " + count);

}

// @Test

public void concatenateTwoArrays() {

int[] array1 = { 1, 2, 3 };

int[] array2 = { 4, 5, 6 };

int leng1 = array1.length;

int leng2 = array2.length;

int[] result = new int[leng1 + leng2];

System.arraycopy(array1, 0, result, 0, leng1);

System.arraycopy(array2, 0, result, leng1, leng2);

System.out.println(Arrays.toString(result));

}

//@Test

public void iterateHashMap() {

HashMap<Integer,String> HM = new HashMap<Integer,String>();

HM.put(2, "Sai");

HM.put(44, "Ravi");

HM.put(12, "Lucky");

for(Map.Entry me:HM.entrySet()) {

System.out.println("Key is: " + me.getKey() + " Value is >> " + me.getValue());

}

}


// @Test

public void duplicateCharsinString() {

String str = "Ravivi";

int count = 0, len = str.length();

char[] cha = str.toCharArray();

System.out.println("Duplicate characters are:");

for (int i = 0; i < len; i++) {

for (int j = i + 1; j < len; j++) {

if (cha[i] == cha[j]) {

System.out.println(cha[j]);

count++;

break;

}

}

}

}


/*

* armstrongNumber 153 = 1*1*1 + 5*5*5 + 3*3*3 = 1 + 125 + 27 = 153 

* If you have a four-digit number lets say 1634 = 1*1*1*1 + 6*6*6*6 + 3*3*3*3 + 4*4*4*4 = 1 + 1296 + 81 + 256 = 1634

*/

@Test

public void armstrongNumber() {

int num = 1634;

int val = 1, armst=0;


while(num>0) {

val = num%10;

num = num/10;

armst = armst+(val*val*val*val);

}

System.out.println(armst);

}

// @Test

public void secondThirdLargEleArray() throws IOException, ParseException {

int temp, size;

int[] num = { 11, 22, 43, 56, 77, 3, 9, 67 };

size = num.length;

for (int i = 0; i < size; i++) {

for (int j = i + 1; j < size; j++) {

if (num[i] > num[j]) {

temp = num[i];

num[i] = num[j];

num[j] = temp;

}

}

}

System.out.println(Arrays.toString(num));

System.out.println(num[size - 2]); // second largest

System.out.println(num[size - 3]); // third largest

// Second Way

int array[] = { 10, 20, 25, 63, 96, 57 };

int size1 = array.length;

Arrays.sort(array);

System.out.println("sorted Array ::" + Arrays.toString(array));

int res = array[size1 - 2];

System.out.println("2nd largest element is ::" + res);

}

}




No comments:

Post a Comment