[Go to site: main page, start]

0% found this document useful (0 votes)
14 views19 pages

Java Code Examples for Data Structures

Uploaded by

ulookamazing6
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views19 pages

Java Code Examples for Data Structures

Uploaded by

ulookamazing6
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1|Page

HashMapHashSet

1. [Link]---- 2
2. [Link]---- 2

NumberArrays

1. [Link]---- 3
2. [Link]---- 3
3. [Link]---- 4
4. [Link]---- 4
5. [Link]---- 5
6. [Link]---- 5
7. [Link]---- 6
8. [Link]---- 6

Numbers

1. [Link]---- 7
2. [Link]---- 7
3. [Link]---- 8
4. [Link]---- 8
5. [Link]---- 9
6. [Link]---- 9
7. [Link]---- 10
8. [Link]---- 10
9. [Link]---- 11
10. [Link]---- 11
11. [Link]---- 12
12. [Link]---- 12

StringArrays

1. [Link]---- 13
2. [Link]---- 13
3. [Link]---- 14
4. [Link]---- 14
5. [Link]---- 15
6. [Link]---- 15
7. [Link]---- 16
8. [Link]---- 16
9. [Link]---- 17
2|Page

Strings

1. [Link]---- 17
2. [Link]---- 18
3. [Link]---- 18
4. [Link]---- 18

[Link]----
package HashMapHashSet;
import [Link];
import [Link];

public class Hashmap {

public static void main(String[] args) {


HashMap<Integer,String> a=new HashMap<>();
[Link](1,"soujanya");
[Link](2,"tulasi");
[Link](3,"ram");
[Link](4,"lavanya");
// [Link]([Link](1));
for([Link]<Integer,String> b:[Link]()) {
[Link]("Key is: "+[Link]()+" Value is: "+[Link]());
}
}
}

[Link]----
package HashMapHashSet;

import [Link];
import [Link];

public class RemoveDuplicatesInArray {

public static void main(String[] args) {


int a[]= {1,2,1};
Set<Integer> b=new HashSet<>();
for(int num: a) {
[Link](num);
}
[Link](b);
}
}
3|Page

[Link]
package NumberArrays;
import [Link];

public class EvenOddCount {

public static void main(String[] args) {


int a[]= {1,2,2};
[Link](a);
int evencount=0;
int oddcount=0;
for(int i=0;i<[Link];i++)
{
if(a[i]%2==0)
{
evencount=evencount+1;
}else {
oddcount=oddcount+1;
}
}
[Link]("even numbers is "+evencount);
[Link]("odd numbers is "+oddcount);
}

[Link]
package NumberArrays;

public class FirstLargestInArray {

public static void main(String[] args) {


int a[]= {2,9,3,4,1,10};
int first=a[0];
for(int i=1;i<[Link];i++)
{
if(a[i]>first)
{
first=a[i];
}
}
[Link](first);

}
4|Page

[Link]----
package NumberArrays;

public class LargestandSmallestElement {

public static void main(String[] args) {


int a[]= {2,1,3,6,9,7,0};
int largest=a[0];
int smallest=a[0];
for(int i=0;i<[Link];i++) {
if(a[i]>largest) {
largest=a[i];
}
if(a[i]<smallest) {
smallest=a[i];
}
}[Link]("Largest number is "+largest);
[Link]("smallest number is "+smallest);
}
}

[Link]----
package NumberArrays;

public class MinMaxOfArray {

public static void main(String[] args) {


int a[]= {1,2,3,4,5,9};
int max=a[0];
int min=a[0];
for(int i=1;i<[Link];i++) {
if(a[i]>max) {
max=a[i];
}
}[Link](max);
for(int i=1;i<[Link];i++) {
if(a[i]<min) {
min=a[i];
}
}[Link](min);
}
}
5|Page

[Link]----
package NumberArrays;
import [Link];

public class nonRepeatedEleArray {

public static void main(String[] args) {


int a[]= {1,1,2,2,3,4,5,5,6,6};
[Link](a);
for(int i=0;i<[Link];i++) {
int count=0;
for(int j=0;j<[Link];j++) {
if(a[i]==a[j]) {
count=count+1;
}
}
if(count==1) {
[Link](a[i]);
}
}
}
}

[Link]----
package NumberArrays;

public class SearchElemInArray {

public static void main(String[] args) {


int a[]= {1,2,3,4,5};
int searchelem=5;
boolean flag=false;
for(int i=0;i<[Link];i++) {
if(a[i]==searchelem) {
[Link]("Element is found at index: " +i);
flag=true;
break;
}
}if(flag==false) {
[Link]("Element is not found");
}
}
}
6|Page

[Link]----
package NumberArrays;

public class SecondLargestInArray {

public static void main(String[] args) {


int a[] = { 8, 2, 7, 9, 5, 6, 10, 11 };
int first = a[0];
int second = a[0];
for (int i = 1; i < [Link]; i++)
{
if (a[i] > first)
{
second = first;
first = a[i];
} else if (a[i] > second)
{
second = a[i];
}
}
[Link](second);
}
}

[Link]----
package NumberArrays;

public class SumOfNumsArray {

public static void main(String[] args) {


String[] a= {"1","q","#","5"};
int sum=0;
for(String element:a) {
try {
int num=[Link](element);
sum=sum+num;
}
catch(NumberFormatException e){
//ignore noninteger elements

}
}[Link](sum);
}
}
7|Page

[Link]----
package Numbers;

public class ArmstrongNumber {

public static void main(String[] args) {


// 153 is with 1 cube+5 cube+3 cube=153
int num= 153;
int d=num;
int arm = 0;
int a,b;
while (num>0) {
a=num%10;//take last num
num=num/10;//remove last num
arm=arm+a*a*a;
}
if (d==arm) {
[Link]("Given Number is armstrong");
} else {
[Link]("Given Number is not armstrong");
}
}
}

[Link]----
package Numbers;

public class CountOfEvenOddNumbers {


public static void main(String[] args) {
int num = 22213;
int even = 0;
int odd = 0;
while (num > 0) {
int res = num % 10;
if (res % 2 == 0) {
even++;
} else {
odd++;
}
num = num / 10;
}
[Link]("Even count is " + even);
[Link]("Odd count is " + odd);
}
}
8|Page

[Link]----
package Numbers;

public class Factorial {

public static void main(String[] args) {

int num = 5;

long factorial = 1;

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

factorial = factorial * i;

[Link](factorial);

[Link]----
package Numbers;

public class FibonacciSeries {

public static void main(String[] args) {


// 0 1 1 2 3 5 8

int n1=0;
int n2=1;
int sum=0;
[Link](n1+" "+n2);
for(int i=2;i<=10;i++) {
sum=n1+n2;
[Link](" "+sum);
n1=n2;
n2=sum;
}
}
}
9|Page

[Link]----
package Numbers;

public class GivenNumOddOrEven {

public static void main(String[] args) {


int a=2021;
if(a%2==0) {
[Link]("Given number "+a+" is prime");
}else {
[Link]("Given number "+a+" is not prime");
}

}
}

[Link]----
package Numbers;

public class NumberReverse {

public static void main(String[] args) {


int num=1234;
int reverse=0;
while(num!=0)
{
reverse=reverse*10+num%10;//take remainder which is last num
num=num/10;//remove last num
}
[Link]("Reverse number is "+reverse);
}

}
10 | P a g e

[Link]----
package Numbers;

public class Palindrome {

public static void main(String[] args) {


int num = 121;
int orgnum = num;
int rev = 0;
while (num != 0) {
rev = rev * 10 + num % 10;
num = num / 10;// remove last digit
}
if (rev == orgnum) {
[Link]("Number is palindrome");
} else {
[Link]("Number is not palindrome");
}
}
}

[Link]----
package Numbers;

public class PrimeOrNot {

public static void main(String[] args) {


int a=4;
int count=0;
for(int i=1;i<=a;i++) {
if(a%i==0) {
count=count+1;
}
}
if(count==2) {
[Link]("Given number is prime");
}
else {
[Link]("Given number is not prime");
}
}

}
11 | P a g e

[Link]----
package Numbers;

public class SumOfDigits {

public static void main(String[] args) {


int num = 123;
int sum = 0;
while (num > 0) {
sum = sum + num % 10;// gives last digit of number
num = num / 10;// removes last digit
}
[Link](sum);

[Link]----
package Numbers;

public class SwappingOfNumbers {

public static void main(String[] args) {


int a=123;
int b=456;
[Link]("Values before swapping are:" +a+" "+b);
int c=a;
a=b;
b=c;
[Link]("Values after swapping are:" +a+" "+b);
}
}
12 | P a g e

[Link]----
package Numbers;

public class SwapWithout3rdVariable {

public static void main(String[] args) {


int a=5;
int b=10;
[Link]("Numbers Before Swipping: "+a+" "+b);
a=a+b;
b=a-b;
a=a-b;
[Link]("Numbers After Swipping: "+a+" "+b);

[Link]----
package Numbers;

public class TotalNumberOfDigits {

public static void main(String[] args) {


int num=12345;
int total=0;
while(num>0)
{
num=num/10;//remove last digit one by one
total++;
}
[Link](total);
}

}
13 | P a g e

[Link]----
package StringArrays;
import [Link];
public class Anagram {
//Anagram is formation of word with same letters given words
public static void main(String[] args) {
String a = "army";
String b = "Mary";
char[] c = [Link]().toCharArray();
char[] d = [Link]().toCharArray();
[Link](c);
[Link](d);
if ([Link](c, d)) {
[Link]("Given strings are anagram");
}
else {
[Link]("Given strings are not anagram");
}
}
}
[Link]----
package StringArrays;
public class CountOfRepeatedWords {
public static void main(String[] args)
{
String a = "hi hi souji";
String b[] = [Link](" ");
int count;
for (int i = 0; i < [Link]; i++)
{
count = 1;
for (int j = i + 1; j < [Link]; j++)
{
if (b[i].equals(b[j]))
{
count = count + 1;
b[j] = "0";
}
}
if (b[i] != "0") {
[Link]("Number of occurances of given string " + b[i] + " is: "
+ count);
}
}
}
}
14 | P a g e

[Link]----
package StringArrays;

public class DuplicateCharsCount {

public static void main(String[] args) {

String a = "ccccccharacters";
char[] b = [Link]();
int count;
for (int i = 0; i < [Link]; i++) {
count = 1;
for (int j = i + 1; j < [Link]; j++) {
if (b[i] == b[j]) {
count = count + 1;
b[j] = 0;
}
}
if (b[i] != 0) {
[Link](b[i] + " is: " + count);
}
}
}
}

[Link]----
package StringArrays;

public class EachWordReverseInString {

public static void main(String[] args) {


String a="java program is very easy";
String[] b=[Link](" ");
String rev="";
for(int i=0;i<[Link];i++) {
String c=b[i];
String revword="";
for(int j=[Link]()-1;j>=0;j--) {
char ch=[Link](j);
revword=revword+ch;
}rev=rev+revword+" ";
}[Link](a);
[Link](rev);
}
}
15 | P a g e

[Link]----
package StringArrays;
public class FirstNonRepeatedChar {
public static void main(String[] args) {
String a="hiibe";
char[] b=[Link]();
char nondups=' ';
int count=0;
for(int i=0;i<[Link];i++) {
count=1;
for(int j=i+1;j<[Link];j++) {
if(b[i]==b[j]) {
count=count+1;
b[j]=0;
}
}
if(b[i]!=0) {
if(count<=1) {
[Link](b[i]);
}
}
}
}
}

[Link]----
package StringArrays;
public class NonRepeatedChars {
public static void main(String[] args) {
String a="hii";
char[] b=[Link]();
int count=0;
for(int i=0;i<[Link];i++) {
count=1;
for(int j=i+1;j<[Link];j++) {
if(b[i]==b[j]) {
count=count+1;
b[j]=0;
}
}
if(b[i]!=0) {
if(count<=1)
[Link](b[i]);
}
}
}
}
16 | P a g e

[Link]----
package StringArrays;

public class NoOfCharsInString {

public static void main(String[] args) {


String a="Soujanya";
char[] b=[Link]();
int count=0;
for(int i=0;i<[Link];i++) {
count=1;
for(int j=i+1;j<[Link];j++) {
if(b[i]==b[j]) {
count=count+1;
b[j]=0;
}
}
if(b[i]!=0) {
[Link](b[i]+" has "+count+" characters");
}
}
}
}

[Link]----
package StringArrays;

public class PermutationsOfGivenString {

public static void main(String[] args) {


String a="abcd";
String prefix="";
String c="";
if([Link]()==0) {
[Link](prefix);
}else
{
for(int i=0;i<[Link]();i++)
{
String b=[Link](0,i)+[Link](i+1);
c=prefix+[Link](i);
}
}
}
}
17 | P a g e

[Link]----
package StringArrays;

public class RemoveDupCharsInString {

public static void main(String[] args) {


String a="cchharacter";
char[] b=[Link]();
int count=0;
for(int i=0;i<[Link];i++) {
count=1;
for(int j=i+1;j<[Link];j++) {
if(b[i]==b[j]) {
count=count+1;
b[j]=0;
}
}
if(b[i]!=0) {
if(count==1 || count>1) {
[Link](b[i]);
}
}
}
}
}

[Link]----
package Strings;

public class CountNoOfWordsInString {

public static void main(String[] args) {


String a="Hi Hello How r";
int count=1;
for(int i=0;i<[Link]()-1;i++) {
if([Link](i)==' ' && [Link](i+1)!=' ') {
count=count+1;
}
}
[Link](count);
}
}
18 | P a g e

[Link]----
package Strings;

public class CountOfGivenChar {


public static void main(String[] args) {
String a = "Soujanyapanasa";
int totalcount = [Link]();
int afterremovechar = ([Link]("a", "")).length();
int countofwantedchar = totalcount - afterremovechar;
[Link]("Number of occurances of given char is " + countofwantedchar);
}
}

[Link]----
package Strings;

public class Pyramid {


public static void main(String[] args) {
for (int i = 0; i <= 5; i++) {
[Link]("");// to start row
for (int j = 1; j <= i; j++) {
[Link]("* ");// to print *
}
[Link]();// to move next line
}
}
}

[Link]----
package Strings;

public class StringReverse {

public static void main(String[] args) {


String a = "ABCD";
String rev = "";

for (int i = [Link]() - 1; i >= 0; i--) {


rev = rev + [Link](i);
}
[Link](rev);
}
}
19 | P a g e

Common questions

Powered by AI

A number is prime if it has only two divisors: one and itself. The provided program iterates from 1 to the number in question, counting how many numbers evenly divide it. If this count equals two, the number is prime; otherwise, it is not. The logic hinges on the fact that prime numbers are only divisible by 1 and themselves, which ensures that only two counts result in its primality .

Reversing an entire string involves iterating backwards from the end of the string to the beginning, appending each character to form the reversed version. To reverse each word individually while leaving the overall sequence untouched, the string is split into words, each word is reversed using a similar backward iteration, and then re-concatenated, maintaining their order in the initial string .

The algorithm converts the string into a character array and iterates over this array. For each character, a nested iteration counts occurrences of the character within the entire array. If a character appears only once (count equals one), it is printed as non-repeated. This process uses arrays to track and print characters only if they weren’t set to zero previously, which indicates their repetition .

To count even and odd numbers in an array, each element is checked using modulus operation. If an element divided by 2 has a remainder of zero, it is considered even; otherwise, it is odd. For counting even and odd digits in a number, the number is continuously divided by 10, and the modulus operation determines whether the last digit (remainder) is even or odd. Both processes track counts using separate even and odd counters, but counting digits involves additional steps of digit extraction .

The second largest element in an array is found by iterating through the array while maintaining two variables, 'first' and 'second', which represent the largest and second largest items tracked so far. Initially, both variables are equal to the first element. As each element is checked, if it is greater than 'first', 'second' is set to 'first', and 'first' is updated to this new largest number. If the current element is larger than 'second' but not greater than 'first', 'second' is updated. This ensures that by the end of the iteration, 'second' holds the value of the second largest element .

The procedure for checking if two strings are anagrams involves first converting each string to lowercase characters and then converting them into character arrays. The arrays are sorted and subsequently compared. If both sorted arrays are identical, the strings are considered anagrams, as this indicates they contain the exact same characters in differing orders .

The pyramid pattern is generated using nested loops. The outer loop controls the number of levels (or rows), while the inner loop prints spaces first and then asterisks in increasing amounts per level. For each iteration of the outer loop, one more asterisk is printed on the next level, forming a triangular shape. This series of loops positions the stars symmetrically, creating a visual pyramid .

Swapping two numbers without a third variable can be achieved using arithmetic operations. The program adds both numbers and assigns the result to the first variable. It then subtracts the new value of the first variable with the second variable’s initial value, storing the result in the second variable. Finally, it re-assigns the first variable by subtracting the modified second variable from the cumulative sum stored in the first variable. This sequence effectively swaps the values without auxiliary storage .

The algorithm initializes the largest and smallest variables as the first element of the array. It then iterates through the array, updating the largest variable if it encounters a value greater than the current largest, and updating the smallest variable if it encounters a value less than the current smallest. This process ensures that by the end of the loop, the largest variable holds the maximum value and the smallest variable holds the minimum value in the array .

A HashSet is used to remove duplicates from an array by leveraging its property of not allowing duplicate values. When an array is iterated over, each element is added to the HashSet. Because the HashSet does not allow duplicates, any repeating values are automatically discarded. The final HashSet contains only unique elements from the array, effectively removing duplicates .

You might also like