## Free Data Structures and Algorithms Course

### How to convert Decimal number to Binary number and vice versa in Java ?.

Program to implement how to convert Decimal number to Binary number and vice versa in Java.

```package com.hubberspot.convertors;

public class DecimalToBinary {

public static void main(String[] args) {

// Create a decimal number
int decimalNumber = 345;

// In order to convert a number from decimal
// to binary we use Integer class static method
// toBinaryString() , it returns back a string
// representation of binary value of the parameter
// passed to it
String binary = Integer.toBinaryString(decimalNumber);

// printing out the converted value on the console
System.out.println("Binary value of the " + decimalNumber + " is : "
+ binary);

// In order to convert binary number back to decimal number
// we use Integer class static method by name parseInt()
// it takes a string parameter which is binary string and
// second parameter as the radix which is decimal format
int originalDecimalNumber =  Integer.parseInt(binary, 2);

// printing out the binary and decimal number
System.out.println("Decimal value of the " + binary + " is : "
+ originalDecimalNumber);

}

}

```

Output of the program :

### How to display or get list of months names in Java ?.

Program to implement how to display or get list of months names in Java

```package com.hubberspot.lists;

import java.text.DateFormatSymbols;

public class MonthsListDemo {

public static void main(String[] args) {

// Create a DateFormatSymbols instance
DateFormatSymbols dfs = new DateFormatSymbols();

// DateFormatSymbols instance has a method by name
// getMonths() which returns back an array of
// months name
String[] arrayOfMonthsNames = dfs.getMonths();

// loop over each month name and printing on the
// console
for( String monthName : arrayOfMonthsNames ) {

System.out.println(monthName);

}

dfs = new DateFormatSymbols();

// DateFormatSymbols instance has a method by name
// getShortMonths() which returns back an array of
// months name in short forms
String[] arrayOfShortMonthsNames = dfs.getShortMonths();

// loop over each month name and printing on the
// console
for( String monthName : arrayOfShortMonthsNames ) {

System.out.println(monthName);

}

}

}

```

Output of the program :

### Write a menu‐driven class to accept a number from the user and check whether it is a Perfect number or not in Java.

Program to demonstrate a menu‐driven class to accept a number from the user and check whether it is a Perfect number or not in Java.

Perfect number – a number is called a Perfect number if it is equal to the sum of its factors other
than the number itself. Example: 6 = 1 + 2 + 3.

```package com.hubberspot.java.example;

import java.util.Scanner;

public class PerfectNumberTest {

public static void main(String[] args) {

char program;
Scanner scanner = new Scanner(System.in);
do {

System.out.println("Press 'P' for Perfect Number Test or 'E' for Exit");

program = scanner.nextLine().toUpperCase().charAt(0);

if(program != 'P' && program != 'E') {
System.out.println();
System.out.println("You entered : " + program);
System.out.println("Please enter P or E to proceed ... try again");
System.out.println();
continue;
}
else {
switch( program )
{
case 'P':
System.out.print( "Enter number for Perfect Number checking: " );

int number = scanner.nextInt();
String line = scanner.nextLine();

if( isPerfectNumber( number ) )
{
System.out.println( number + " is a perfect number." );
}
else
{
System.out.println( number + " is not a perfect number." );
}
break;
}
}

System.out.println();

if( program == 'E') {
System.out.println("Exiting from the program...");
}
}
while(program != 'E');

}

private static boolean isPerfectNumber(int number) {

int sumOfFactors = 0;

for( int i = 1; i < number; i++ )
{
if( (number % i ) == 0 )
{
sumOfFactors = sumOfFactors + i;
}
}
return( sumOfFactors == number );

}

}

```
Output of the program :

### Write a menu‐driven class to accept a number from the user and check whether it is a Palindrome number or not in Java.

Program to demonstrate a menu‐driven class to accept a number from the user and check whether it is a Palindrome number or not in Java.

Palindrome number – a number is a Palindrome which when read in reverse order is same as read
in the right order. Example: 121, 11, 15451, etc.

```package com.hubberspot.java.example;

import java.util.Scanner;

public class PalindromeTest {

public static void main(String[] args) {

char program;
Scanner scanner = new Scanner(System.in);
do{

System.out.println("Press 'P' for Palindrome Test or 'E' for Exit");

program = scanner.nextLine().toUpperCase().charAt(0);

if(program != 'P' && program != 'E') {
System.out.println();
System.out.println("You entered : " + program);
System.out.println("Please enter P or E to proceed ... try again");
System.out.println();
continue;
}
else {
switch( program )
{
case 'P':
System.out.print( "Enter number for Palindrome checking: " );

int number = scanner.nextInt();
String line = scanner.nextLine();

if( isPalindrome( number ) )
{
System.out.println( number + " is a palindrome." );
}
else
{
System.out.println( number + " is not a palindrome." );
}
break;
}
}

System.out.println();

if( program == 'E') {
System.out.println("Exiting from the program...");
}
}
while(program != 'E');

}

private static boolean isPalindrome(int number) {

int reverse = 0;
int original = number;

while(number > 0) {
int digit = number % 10;
reverse = reverse * 10 + digit;
number = number / 10;
}
return (reverse == original);
}

}

```

Output of the program :

Video tutorial to demonstrate how to check whether a given string is palindrome or not through a Java program.

### How to display or get list of week days names in Java ?.

Program to implement how to display or get list of week days names in Java

```package com.hubberspot.lists;

import java.text.DateFormatSymbols;

public class WeekDaysList {

public static void main(String[] args) {

// Create a DateFormatSymbols instance
DateFormatSymbols dfs = new DateFormatSymbols();

// DateFormatSymbols instance has a method by name
// getWeekdays() which returns back an array of
// week days name
String[] arrayOfWeekDaysNames = dfs.getWeekdays();

// loop over each day name and printing on the
// console
for( String dayName : arrayOfWeekDaysNames ) {

System.out.println(dayName);

}

dfs = new DateFormatSymbols();

// DateFormatSymbols instance has a method by name
// getShortWeekdays() which returns back an array of
// week days name in short forms
String[] arrayOfShortWeekDaysNames = dfs.getShortWeekdays();

// loop over each day name and printing on the
// console
for( String dayName : arrayOfShortWeekDaysNames ) {

System.out.println(dayName);

}

}

}

```

Output of the program :

### How to display or get list of country names in Java ?.

Program to implement how to display or get list of country names in Java

```package com.hubberspot.lists;

import java.util.Locale;

public class CountrysListDemo {

public static void main(String[] args) {

// Using Locale class static method getISOCountries()
// we extract a list of all 2-letter country codes
// defined in ISO 3166. Can be used to create Locales.

String[] countries = Locale.getISOCountries();

// Loop each country
for(int i = 0; i < countries.length; i++) {

String country = countries[i];
Locale locale = new Locale("en", country);

// Get the country name by calling getDisplayCountry()
String countryName = locale.getDisplayCountry();

// Printing the country name on the console
System.out.println(i+1 + " : " + countryName);

}

}

}

```
Output of the program :

.
.
.
.
.

### How to get information about the Environment Variables used through a Java program ?.

Program to demonstrate how to get information about the Environment Variables used through a Java program.

```package com.hubberspot.environmentVariables;

import java.util.Map;
import java.util.Set;

public class EnvironmentVariablesDemo {

public static void main(String[] args) {

// In order to get information about the environment variables
// used we call java.lang.System class's getenv() method
// It retirns back a map storing environment variable name and
// value
Map < String, String > environmentVariableMap = System.getenv();

// We get all the names of environment variables as a set
// using keySet() method of map of environment variables
Set < String > keySet = environmentVariableMap.keySet();

// We loop each and every element of the map
// and print the name and value of the environment variables
for(String environmentKey : keySet){

String environmentValue = environmentVariableMap.get(environmentKey);

System.out.println(environmentKey + " = " + environmentValue);

}

}

}

```

Output of the program :

### How to know on which Java Version our current Java application is running ?.

Program to demonstrate how to know on which Java Version our current Java application is running.

```package com.hubberspot.java.version;

public class JavaVersion {

public static void main(String[] args) {

// In order to know which version of java
// is been used by your current application
// we can get the version of Java by
// using getProperty() method of the
// java.lang.System class and passing
// the property name as "java.version"
String javaVersion = System.getProperty("java.version");

// Printing out the Java version on the console
System.out.println("Java Version : " + javaVersion);

}

}

```

Output of the program :

### How get and use minimum and maximum values of primitive data types through Java program ?.

Program to demonstrate how get and use minimum and maximum values of primitive data types in Java.

```package com.hubberspot.primitive.examples;

public class MinimumAndMaximumDemo {

public static void main(String[] args) {

// Create a Byte object holding minimum
// and maximum value of byte primitive
// In order to get minimum and maximum value
// we use Wrapper classes MAX_VALUE and MIN_VALUE constant
Byte minimumByteValue = Byte.MIN_VALUE;
Byte maximumByteValue = Byte.MAX_VALUE;

System.out.println("Minimum byte value is : " + minimumByteValue);
System.out.println("Maximum byte value is : " + maximumByteValue);

// Create a Short object holding minimum
// and maximum value of byte primitive
// In order to get minimum and maximum value
// we use Wrapper classes MAX_VALUE and MIN_VALUE constant
Short minimumShortValue = Short.MIN_VALUE;
Short maximumShortValue = Short.MAX_VALUE;

System.out.println("Minimum short value is : " + minimumShortValue);
System.out.println("Maximum short value is : " + maximumShortValue);

// Create an Integer object holding minimum
// and maximum value of byte primitive
// In order to get minimum and maximum value
// we use Wrapper classes MAX_VALUE and MIN_VALUE constant
Integer minimumIntegerValue = Integer.MIN_VALUE;
Integer maximumIntegerValue = Integer.MAX_VALUE;

System.out.println("Minimum integer value is : " + minimumIntegerValue);
System.out.println("Maximum integer value is : " + maximumIntegerValue);

// Create a Long object holding minimum
// and maximum value of byte primitive
// In order to get minimum and maximum value
// we use Wrapper classes MAX_VALUE and MIN_VALUE constant
Long minimumLongValue = Long.MIN_VALUE;
Long maximumLongValue = Long.MAX_VALUE;

System.out.println("Minimum long value is : " + minimumLongValue);
System.out.println("Maximum long value is : " + maximumLongValue);

// Create a Float object holding minimum
// and maximum value of byte primitive
// In order to get minimum and maximum value
// we use Wrapper classes MAX_VALUE and MIN_VALUE constant
Float minimumFloatValue = Float.MIN_VALUE;
Float maximumFloatValue = Float.MAX_VALUE;

System.out.println("Minimum float value is : " + minimumFloatValue);
System.out.println("Maximum float value is : " + maximumFloatValue);

// Create a Double object holding minimum
// and maximum value of byte primitive
// In order to get minimum and maximum value
// we use Wrapper classes MAX_VALUE and MIN_VALUE constant
Double minimumDoubleValue = Double.MIN_VALUE;
Double maximumDoubleValue = Double.MAX_VALUE;

System.out.println("Minimum double value is : " + minimumDoubleValue);
System.out.println("Maximum double value is : " + maximumDoubleValue);

}

}

```

Output of the program :

### How to check whether an ArrayList contains an element specified in Java ?.

Program to implement how to check whether an ArrayList contains an element specified in Java.

```package com.hubberspot.arraylist;

import java.util.ArrayList;
import java.util.List;

public class ArrayListContainsDemo {

public static void main(String[] args) {

// Create a ArrayList object which can store
// collection of String objects
List< String > stringList = new ArrayList< String >();

// Add few String objects to it

// Lets create an String object and check
// whether ArrayList created above contains it
String name = "Neha";

// In order to check whether ArrayList contains an element
// or not we use list's contains(), which
// Returns true if this list contains the specified element.
if( stringList.contains(name) ) {

System.out.println("The list contains the element : " + name);

}
else {

System.out.println("The list does not contains the element : " + name);

}

name = "Dhwani";

if( stringList.contains(name) ) {

System.out.println("The list contains the element : " + name);

}
else {

System.out.println("The list does not contains the element : " + name);

}

}

}

```

Output of the program :

### How to get and print size of an ArrayList in Java ?.

Program to implement how to get and print size of an ArrayList in Java.

```package com.hubberspot.arraylist;

import java.util.ArrayList;
import java.util.List;

public class ArrayListSizeDemo {

public static void main(String[] args) {

// Create a ArrayList object which can store
// collection of String objects
List< String > stringList = new ArrayList< String >();

// Add few String objects to it

// In order to get number of objects stored in
// a list we can call size() method which will
// return an int value stating the size of ArrayList
int size = stringList.size();

// printing out the size of ArrayList on the console
System.out.println("Size of String ArrayList : " + size);

// Create a ArrayList object which can store
// collection of Integer objects
List< Integer > integerList = new ArrayList< Integer >();

// Add few Integer objects to it

// In order to get number of objects stored in
// a integer list we can call size() method which will
// return an int value stating the size of ArrayList
size = integerList.size();

// printing out the size of ArrayList on the console
System.out.println("Size of Integer ArrayList : " + size);

}

}

```

Output of the program :

### How to fill and clear contents of an Array in Java ?.

Program to implement how to fill and clear contents of an Array in Java.

```package com.hubberspot.arrays;

import java.util.Arrays;

public class ArraysFill {

public static void main(String[] args) {

// Create an array of Strings storing few customers names
String[] customers = {"Dinesh" , "Jonty" , "Mallika" , "Navjinder"};

// print out the customers name in array using Arrays class
// static method by name toString()
System.out.println("Customers Name: " + Arrays.toString(customers));

// To clear contents of array at once we use
// Arrays class static method by name fill()
// It replaces each element of an array by the second
// parameters it takes in
Arrays.fill(customers, null);

System.out.println("Customers Name: " + Arrays.toString(customers));

// Here instead of null now we pass a String by name "Radhika"
// it replaces each and every element of array to this String

// Print the array
System.out.println("Customers Name: " + Arrays.toString(customers));

// Again assigning null and clearing out the contents
Arrays.fill(customers, null);

System.out.println("Customers Name: " + Arrays.toString(customers));

}

}

```

Output of the program :

### How to read and write a file in Java 7 using java.nio API ?

Program to demonstrate how to read and write a file in Java 7 using java.nio API.

```package com.hubberspot.java7;

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public static void main(String[] args) {

// Create a path to the file which is
// to be written and read later
// here "D:\\books\\java\\" is the address
// to reach the file created by name "hubberspot.txt"
Path filePath = Paths.get("D:\\books\\java\\hubberspot.txt");

try {

// First we check whether file already exists
// at the filePath by using Files class static
// method by name exists()
if (!Files.exists(filePath)) {

try {

// Second we create a file at
// the specified filePath by using
// Files class createFile() method.
Files.createFile(filePath);

} catch (IOException e) {

e.printStackTrace();
}
}

// Create a BufferedWriter instance by calling
// Files class newBufferedWriter() method which
// returns back BufferedWriter object
// This method takes in three parameters such as:
// 1. Path to the file created above
// 2. Charsets for the format of the file
// 3. Open options which defines the standard open options
BufferedWriter writer = Files.newBufferedWriter(filePath,
StandardCharsets.UTF_16, StandardOpenOption.WRITE);

// Here we use write() method to write some content
// to the file at the path specified above
writer.write("Hello World !!! \n");
writer.write("Welcome to Hubberspot.com.\n");
writer.write("Learn Java By Examples !!!!... \n");

// close the writer
writer.close();

} catch(Exception e) {

e.printStackTrace();

}

try {

// Create a BufferedReader instance by calling
// Files class newBufferedReader() method which
// This method takes in two parameters such as:
// 1. Path to the file created above
// 2. Charsets for the format of the file
StandardCharsets.UTF_16);

String line;

// To read contents of file line by line
// method and prints contents to console

System.out.println(line);

}

}
catch(Exception e) {

e.printStackTrace();

}

}
}

```

Output of the program :

### How to Copy and Move a file in Java 7 using java.nio ?.

Program to implement how to Copy and Move a file in Java 7 using java.nio

```package com.hubberspot.java7;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import static java.nio.file.StandardCopyOption.*;

public class CopyMoveFile {

public static void main(String[] args) {

// Let say we have a file placed at the directory
// D:\books\java by the name CopyAndMove.txt and
// we want to copy or move it to a different directory
// by name D:\books\CopyAndMove.
// In order to do that we create two Path instances
// in which one path represent the source and other
// represents the target
Path source = Paths.get("D:\\books\\java\\CopyAndMove.txt");
Path target = Paths.get("D:\\books\\CopyAndMove\\CopyAndMove.txt");

// In order to take a backup we usually use copy()
// method of Files class by passing three parameters
// such as source from where it picks the file
// the target where it tranfers the file and
// lastly the CopyOption which tells that
// whether to replace existing file if it exists
// by the name provided already.
try {

Files.copy(source, target, REPLACE_EXISTING);

} catch (IOException e) {

e.printStackTrace();
}

// In order to move a file completely we usually
// use move() method of Files class by passing
// three parameters such as source from
// where it picks the file the target where
// it tranfers the file and lastly the
// CopyOption which tells that whether
// to replace existing file if it exists
// by the name provided already.

try {

Files.move(source, target, REPLACE_EXISTING);

} catch (IOException e) {

e.printStackTrace();
}

}

}

```

### How to create and delete a file in Java 7 using java.nio ?

Program to implement how to create and delete a file in Java 7 using java.nio ?.

```package com.hubberspot.java7;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class CreateAndDeleteFile {

public static void main(String[] args) {

// Create a path to the file which is
// to be created and deleted later
// here "D:\\books\\java\\" is the address
// to reach the file created by name "hubberspot.java"
Path filePath = Paths.get("D:\\books\\java\\hubberspot.java");

// First we check whether file already exists
// at the filePath by using Files class static
// method by name exists()
if (!Files.exists(filePath)) {

try {

// Second we create a file at
// the specified filePath by using
// Files class createFile() method.
Files.createFile(filePath);

} catch (IOException e) {

e.printStackTrace();
}
}

// In order to delete there must be a file,
// here we check whether file already exists
// at the filePath by using Files class static
// method by name exists()
if (Files.exists(filePath)) {

try {

// here we delete a file at
// the specified filePath by using
// Files class delete() method.
Files.delete(filePath);

} catch (IOException e) {

e.printStackTrace();
}
}
}
}

```

© 2021 Learn Java by Examples Template by Hubberspot