Prime Number Series Java Program

Prime Number Series Program



The series of Prime Numbers all the Prime numbers which are less then the number provided by the user.

The Java Code starts by asking the user to enter a number, and then displays all the Prime Numbers which are less then or equal to that number. This program generates all the prime numbers less then a number, so it is a series of Prime Numbers.

The Java Code is provided below:-

///////////////////////////////////////

package developer;

import java.util.Scanner;

public class PrimeNumberSeries {

public static void main(String[] args)
{ 
int numero = 0;
System.out.println("Enter a number:");
Scanner takeValue = new Scanner(System.in); 
if(takeValue.hasNextInt())
{
numero = takeValue.nextInt();
} 
System.out.println("All the Prime Numbers, which are less then or equal to the number entered are:");
checkPrimeNumber(numero);
}

static void checkPrimeNumber(int val)
{
int tapper = 0; 

for (int i=2; i < val; i++ ){
if(val%i == 0)
{ 
tapper = 0;
break;
} 
else
{
tapper = 1;
}
}
if(tapper == 1 || val == 2)
{
System.out.print(val+" ");
if(val > 2)
checkPrimeNumber(val-1); 
}
else
{
if(val > 2)
checkPrimeNumber(val-1);
else
System.out.println("Number out of range"); 
} 
}
} 

///////////////////////////////////////////////

Factors of a number in Java Program

Factors of a Number



The Java Program starts by prompting the user to enter a number, and then displays the all the factors of the number entered by the user.

The factors of a number are the numbers which divide the number entered by the user completely.

The Java Example Code is given below:-

/////////////////////////////////////////

package developer;

import java.util.Scanner;

public class Factor {

/**
* @param args
*/
public static void main(String[] args) {
System.out.println("Enter a number whose factors are desired: ");
Scanner scanNum = new Scanner(System.in);
int numFac = 0;
if(scanNum.hasNextInt())
{
numFac = scanNum.nextInt();
}

System.out.println("The Factors of the entered number are:-");

for(int i = 1; i <= numFac; i++)
{
if(numFac%i == 0)
{
System.out.print(i+" ");
}
}

}

}

/////////////////////////////////////////

Prime Factors Java Program

Prime Factors



Prime Factors are those numbers which are factors of the entered number, and also are Prime in nature. For being a factor, the number needs to divide completely the entered number. For example, f I say that the user entered 20, then the factors of this number are 1 2 4 5 10 and 20, but when we say about Prime Factors then out of these only 2 and 5 are prime, so 2 and 5 are the Prime factors of the number 20 which is entered by the user.

The complete Java code is given below:-

////////////////////////////////////////

package developer;

import java.util.Scanner;

public class PrimeFactor {

static int primeCheck = 1;

public static void main(String[] args) {
System.out.println("Enter a number whose Prime factors are desired: ");
Scanner numS = new Scanner(System.in);
int numPriFac = 0;
if(numS.hasNextInt())
{
numPriFac = numS.nextInt();
}

System.out.println("All the Prime Factors of the entered number are:-");

for(int tap = 1; tap <= numPriFac; tap++)
{
if(numPriFac%tap == 0)
{
for(int primeTest = 2; primeTest < tap; primeTest++)
{
if(tap%primeTest == 0)
{
primeCheck = 1;
break;
}
else
{
primeCheck = 0;
}
}
if(primeCheck == 0 || tap == 2)
{
System.out.print(tap+ " ");
} 
}
}
}
}

///////////////////////////////////////////

Addition of two Numbers in Java Program

Addition of two numbers Java Program



The code makes use of Scanner for getting the input from the console.

The code starts by asking the user to enter two numbers to be added. The user enters the first number, press enter, and then enters the second number and then press enter again. After this the code computes the addition of these two numbers.

The Java Code is provided below:-

//////////////////////////////////////

package developer;

import java.util.Scanner;

public class AddTwoNumber {

/**
* @param args
*/
public static void main(String[] args) {
System.out.println("Enter the first and second numbers");
//Get the first number
Scanner scanOne = new Scanner(System.in);
//Get the second number
Scanner scanTwo = new Scanner(System.in);

if(scanOne.hasNextInt() && scanTwo.hasNextInt())
{
System.out.print("The sum of the two numbers entered is: ");
System.out.println(scanOne.nextInt()+scanTwo.nextInt());
}

}

}

//////////////////////////////////////////


Remove Extension of File Java Code

Remove Extension of a File


The operation is a simple one and is crucial in case of file handling. Though mostly we need to remove the file extension before processing the file, there may be other requirements that ask for this requirement.

Anyhow the Java Code is provided below:-

//////////////////////////////

package developer;

import java.util.Scanner;

public class RemoveFileExtension {

public static void main(String[] args) {

String fileRemExt = null;

System.out.println("Enter a valid file name whose extension is to be removed:");

Scanner rem = new Scanner(System.in);

if(rem.hasNext())
{
fileRemExt = removeFileExtension(rem.next());
}

if(null != fileRemExt)
{
System.out.println("The file name without extension is: "+fileRemExt);
}
else
{
System.out.println("Not a valid file name");
}

}

//remove the file extension of the file entered
public static String removeFileExtension(String fileName)
{ 
if(null != fileName && fileName.contains("."))
{
return fileName.substring(0, fileName.lastIndexOf("."));
}
return null;
}

}
////////////////////////////////////

Once this code is executed, the output is something like:-

////////////////////////////////////
Output

Enter a valid file name whose extension is to be removed:
test.java
The file name without extension is: test
////////////////////////////////////

Java Code for File Extension

Code for File Extension


The Java code here asks the user to enter a valid file name, and then remove the file name but keep the extension of it. So the user enters a file name and gets the extension of it.

The Java Code is provided below:-

///////////////////////////////////
package developer;

import java.util.Scanner;

public class FileExtension {

/**
* @param args
*/
public static void main(String[] args) {

String fileExt = null;

System.out.println("Enter a valid file name whose extension is desired:");

Scanner scan = new Scanner(System.in);

if(scan.hasNext())
{
fileExt = getFileExtension(scan.next());
}

if(null != fileExt)
{
System.out.println("The extension of the file is: "+fileExt);
}
else
{
System.out.println("Not a valid file name");
}

}

//get the file extension of the file entered
public static String getFileExtension(String filePath)
{
String extension = null;
if(null != filePath && filePath.contains("."))
{
extension = filePath.substring(filePath.lastIndexOf("."), filePath.length()); 
}
return extension; 
}

}

////////////////////////////////////////

When this code is executed, the output is something like as given below:-

//////////////////////////////////////////
Output

Enter a valid file name whose extension is desired:
javadeveloper.java
The extension of the file is: .java
/////////////////////////////////////////

Interface in Java

What is an Interface in Java

Interfaces has been the heart of most of the Java fundamentals and coding, mostly because there existence support Polymorphism, which is one of the four Principle of OOPS apart from Abstraction, Encapsulation and Inheritance.

Interface as the name suggests is a "Contract". Yes you read it right. It is contract between the interface provider and the interface implementer that the methods mentioned in the Interface will be implemented. Mostly Interfaces are used vis a vis Inheritance, and there is much research done before choosing one.

An Interface is like a pure abstract class, with the difference that the all the methods of the interface are abstract, so any class that implements this interface has to implement all the methods mentioned in this interface. That's the law. So actually the interface tells that which methods are to be implemented, but not that how we are going to implement. It is left for the subclasses to decide how to implement this.

One important part of Java is that it supports multiple Implementations, but not multiple Inheritance. So a subclass can implement multiple Interfaces, but cannot extend multiple classes. I will detail on this in a later post where I will tell you that if multiple Inheritance is allowed, then how it may lead to the Deadly Diamond of death. Anyhow that's a bit deviating from the main topic. Our primary concern are the Interfaces.

An example of an Interface is shown below:-

////////////////////////////////////////////

Interface JavaTest{
public static final int val = 3;

public abstract doTest();
public abstract takeResult();
}

////////////////////////////////////////////

Here in this Interface declaration file, the keywords public and abstract are not required for the methods as they are implicit. Moreover the keywords for the variable declared in the Interface are also not required as they are also implicit. 

So any variable declared in an Interface is practically a constant, and all the methods which are declared in the interface have to be implemented by the first concrete subclass that implements this interface.




There is one key point regarding the Interfaces, and that is you cannot declare the methods of the Interface to be final. Remember that final methods cannot be overridden, and an abstract method is useless if we do not override it. That is the main reason that abstract and final are never used together for any method.

Final Methods in Java

Final Methods in Java



The final methods in the Java Programming Language. The Java language provides its users with many resources and tools. There are many features in the Java language that makes it very powerful. Final access modifier is one of those features, that makes Java really solid.

If a method is marked as final, then it implies that it cannot be overridden. So any class that extends the class containing the final methods, cannot override the methods marked final. If any attempt is done to override a final method in a sub class, leads to Java Compiler error.

An example of a final method in a class is:-

/////////////////////////////

class TestFinal{

public final void finalTested(){
//Working of this method
}

//Some other methods

}

/////////////////////////////

The above Java code depicts the use of final when applied to methods.

You may be thinking that what is the advantage of making a method final, though it defies the basic principle of OOPS, that is the final methods are non supportive of inheritance, as they cannot be overridden. It implies that they cannot be extended, and so also makes Polymorphism not feasible for it. 

Hmmm... it implies that there are many drawbacks of the final method, but still Java provides it. So there must be some advantage of it also... Lets check them out.

Think of a scenario, that you have made a class, and you want a particular method to be implemented in exactly a particular way, and one should be never allowed to change this implementation. There are many possibilities for it. Like there are many methods in the Java API, which are guaranteed to work in a fixed way, and there is no way we can change them. This scenario calls for marking the method of the class as final. Later I will tell you about the Template Design Pattern which is based on this concept.

I hope you got my point. Whenever you want the methods to be locked, and should not be allowed to be modified, then final is the keyword to be used. The class can still be inherited since it is not marked final, and so the concept of Inheritance and Polymorphism can easily work here, but only for methods which are not marked as final in the super class. 

Java Code to Read a File

Read a File


This is very important in Java File concept. There are often various scenarios when the data required is to be read from a particular file that is not part of the application.

The external file may be a .txt, .xml, .csv etc. type of file. The thing that matters is that we need to read it in the Java application. The code discussed here is applicable for a .txt file. Though the processing will differ a bit for the other type of files.

I have taken an example, where a file is read from a particular folder. Replace the path with the path of your file, and you are all set to go. I have added extra comments for each line of code, so as to make there purpose clear in the Java Program.

The Java code is provided below:-

///////////////////////////////////////


package developer;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFile {

public static void main(String[] args) throws IOException {

String fileStore = null;

//Note the "\\" used in the path of the file instead of "\",
//this is required to read the path in the String format.
FileReader fr = new FileReader("D:\\JavaCodeFile\\Test.txt");

BufferedReader br = new BufferedReader(fr);

//save the line of the file in a String variable and compare it with null, and continue till null (End of File) is not achieved
while(null != (fileStore = br.readLine()))
{
//Print the file line by line
System.out.println(fileStore);
}

//close the Buffered Reader
br.close();

//Close the File Reader
fr.close();
}
}


///////////////////////////////////////

When the code is executed, it will display the content of the file line by line on the console. for my case the output was as given below. Your output may differ based on the file content.

///////////////////////////////////////


Hello
Welcome to Java Code Online
This is a test file


///////////////////////////////////////

Java Code to Write to a File

Write to a File



There are often various cases when we need to write or save some data in an external file. Java provides a very powerful set of libraries for handling this operation.

First for writing to a file you need to have write permission on it, So first we need to check that whether we can write on it or not. If the file is writable, then we use the FileWriter class provided by Java to perform this operation. This file is part of the java.io package, which includes many powerful classes for handling the Java input output operations.

The writing to a file operation is used in many cases like when we need to save some content in a file, which could be read or used afterward. this file may also be sent to some other application for some other operations required on it.

The Java Code for writing to a file is provided below. We assumed a path as per our local machine. You need to set the path according to your folder structure. This code writes the content in a file. If the file is not present, then it creates one and then write to it. So anyhow your writing operation will be successful.

The Java Code is:-

////////////////////////

package developer;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class WriteToFile {


public static void main(String[] args) throws IOException {
//Note the "\\" used in the path of the file instead of "\",
//this is required to read the path in the String format.
FileWriter fw = new FileWriter("D:\\JavaCodeFile\\WriteTest.txt");
PrintWriter pw = new PrintWriter(fw);

//Write to file line by line
pw.println("Hello guys");
pw.println("Java Code Online is testing");
pw.println("writing to a file operation");

//Flush the output to the file
pw.flush();

//Close the Print Writer
pw.close();

//Close the File Writer
fw.close(); 
}
}


////////////////////////

The beauty of the code lies in its compactness and simplicity of use. Note the use of flush on the PrintWriter Class Object. This helps in writing any buffered output to the file. This ensures that all the content is written to the file, before the writer is closed.

Java Code to Create a File

Create a File


In Java there are various possibilities for File Manipulation and handling. I suppose the simplest of them is regarding creation of a File. There are cases when we need to create a File for backing up some data, or write some important data, or might be some other reason. For all of the above we need to know first of all, how to create a File.

Creating a file is a simple process, and it uses just two methods of the File Class which is in the java.io package. They are:-

1. exists()
2. createNewFile()

The exists() method checks that whether the file exists or not. The createNewFile() method creates new File. Though creation of the File can be easily done by the createNewFile() method, it is a good practice to check that the file exists prior to creation or not. This case is important in scenarios where we need to create a File in case it does not exists, if it exists, then we need to modify it. So here the exists() method is very important, as it checks beforehand that the File exists or not.

The Java Code discussed today starts by declaring a new File at a particular path. You need to configure the path according to your application. I suppose that this is the only change apart from the package name, that you may need to do in this program, so as to compile and run it successfully.

The File is then tested for its existence using the method exists(), and if the file is found to be non existent, then a new File is created using createNewFile() method.

The Java Code is provide below for your reference:-

/////////////////////////////////////////

package developer;

import java.io.File;
import java.io.IOException;

public class CreateFile {

public static void main(String[] args) throws IOException {

File fileTest = new File("D:\\JavaCodeFile\\CreateTest.txt");

//Check for the existence of the file
System.out.println("Does the file exists before execution of the code? ");
System.out.println(fileTest.exists());

if(!fileTest.exists())
{
//Create a new file at the specified path
fileTest.createNewFile();
}

//Check again for the existence of the file
System.out.println("Does the file exists after execution of the code? ");
System.out.println(fileTest.exists());
}
}

/////////////////////////////////////////

The output on my console after compiling the application using the Java compiler and running this program on my JVM was as below:-

/////////////////////////////////////////

Does the file exists before execution of the code? 
false
Does the file exists after execution of the code? 
true

/////////////////////////////////////////

Java Code to Delete a File


Delete a File in Java

Though a very simple process, it is very important. It is one of the most basic aspects of File Handling. So this Java Blog has decided to pick this topic in this tutorial.

The Java Code discussed today, starts by taking the path for the file, and checks for its existence. If the file exists, then the delete() command is fired on it. After deletion of the file, the presence of the file is checked. This step is to ensure that the deletion activity of the file is properly achieved or not.

The Java code is provided below:-

/////////////////////////////////

package developer;

import java.io.File;

public class DeleteFile {

public static void main(String[] args) {

File fileTest = new File("D:\\JavaCodeFile\\WriteTest.txt");

//Check for the existence of the file before deletion of it
System.out.println("Is the file present in the current location before deletion? ");
System.out.println(fileTest.exists());

if(fileTest.exists())
{
//Delete the file
fileTest.delete();
}

//Check for the existence of the file after deletion of it
System.out.println("Is the file present in the current location after deletion? ");
System.out.println(fileTest.exists());
}
}

/////////////////////////////////

This Java Code when executed on my JVM, resulted in the following output.

/////////////////////////////////

Is the file present in the current location before deletion? 
true
Is the file present in the current location after deletion? 
false

/////////////////////////////////

Java Code to Convert Decimal to Binary

Decimal to Binary


A decimal number is known to all of us. It is number whose base value is 10. All the number in normal practice are usually decimal numbers. It implies that decimal numbers can consist of number from 0-9.


A binary number is a number whose base value is 2. It means that a binary number system consists of only 0 and 1. In computers all the data is transferred in the form of binary numbers.

The Java Code presented today, asks the user to enter a decimal number, and displays the binary equivalent of that number.

The Java code is displayed below:-

/////////////////////////////////////////////

package developer;

import java.util.Scanner;

public class DecimalToBinary {

    public static void main(String[] args) {
   
        System.out.println("Enter a decimal number: ");
        Scanner scanStr = new Scanner(System.in);
               
        String num = null;       
       
        //Check for an integer number entered by the user
        if(scanStr.hasNextInt())
        { 
            //Convert the decimal number to binary String
            num = Integer.toBinaryString(scanStr.nextInt());
        }           
       
        System.out.println("The decimal number in binary is: "+num);           
    }
}

/////////////////////////////////////////////

When the code is executed, the output is as shown below:-

/////////////////////////////////////////////

Enter a decimal number: 
23
The decimal number in binary is: 10111

/////////////////////////////////////////////

Java Code to Convert Binary to Decimal

Java Code to Convert Binary to Decimal



Java has deal with many different situations. We discuss a case when a number entered as binary is to be converted to a decimal number. A binary number which consists of only 1 and 0, while a decimal number is a number which consists of numbers between 0-9.

We normally use decimal numbers in our daily purposes. Binary numbers on the other hand are very important and used for computers data transfer.

The Java code for converting a binary number to a decimal number, starts by asking the user to enter a binary number. The result is a decimal number which is displayed to the user. In case the number entered is not a binary number, i.e. it contains numbers other then 0 and 1. In that a NumberFormatException will be thrown. I have catch this exception, so that the developer can use there custom message in that place.

The Java Code is displayed below:-

/////////////////////////////////////

package developer;

import java.util.Scanner;

public class BinaryToDecimal {

    public static void main(String[] args) {
       
        System.out.println("Enter a binary number: ");
        Scanner scanStr = new Scanner(System.in);
               
        int decimalNum = 0;       
               
        if(scanStr.hasNext())
        {    
            try
            {
                decimalNum = Integer.parseInt(scanStr.next(),2);
                System.out.println("Binary number in decimal is: "+decimalNum);   
            }
            catch(NumberFormatException nfe)
            {
                System.out.println("The number is not a binary number.");
            }
        }   
    }
}


/////////////////////////////////////

When this code is executed on my system, the output is as shown below.
/////////////////////////////////////

Enter a binary number: 
10100011
The binary number in decimal is: 163

/////////////////////////////////////

In case the number entered is not a binary number, then the output is as shown below:-

/////////////////////////////////////

Enter a binary number: 
123456
The number is not a binary number.

/////////////////////////////////////
  

JDBC (Java Data Base Connectivity)

JDBC Basics


Types of JDBC Drivers
Type 1:- Bridge drivers. Example JDBC-ODBC Bridge
Type 2:- Native API drivers, partially in Java.
Type 3:-Middleware is involved in communication from client's request and data source.
Type 4:-The client connects directly to DataSource, pure Java drivers.

Establishing the Connection
Two ways:-
1) DriverManager class
2) DataSource interface

Using DriverManager class for making connection
Load the driver:-   Class.forName("oracle.jdbc.driver.OracleDriver");
Define Connection URL:-  String url = "jdbc:oracle:thin:@" + hostName + ":" + portName + ":" + dbName;
Establish Connection:- Connection conn =DriverManager.getConnection(url,username,password);

Using DataSource interface for making connection
InitialContext initContext = new InitialContext(); 
DataSource ds = initContext.lookup("java:comp/env/jdbc/ownDataBase");
Connection con = ds.getConnection();

The above method uses JNDI lookup to get the datasource.

Using Datasource for getting JDBC connection is preferred over DriverManager class.


Character Data Types in Java

Character Data Types in Java

The data types in Java can be categorized in four categories. Character Data Types is the third category after Integer Data Types and Floating Point Data Types.

In Java the Character Data type is of single type. It is:-
1. char (16 bits) (range: 0 to 65535)

We will discuss this data type of Java in detail now.

char
"char data type in Java" has some special features which were not present in its predecessors like C and C++. In Java the "char" Data Type is 16 bit long. Java uses Unicode to represent characters, and so for languages which have long Unicode representations do have characters which require more than 8 bit of data. That makes Java a truly international language, since by using Unicode char set, Java can define any language in the world.

If you have noticed above, then you would have seen that the range of "char" data type is from 0 to 65535, there are no negative chars. The range that the "char" data type enjoy in Java, is truly awesome, and makes Java one of the most global languages in the world.

Regarding functionality of the "char" data type. A "char" data type in Java is capable of handling one character at a time. For example:-

char testing = 'j';

Here the variable testing is of "char" Data Type, and is assigned equal to the character 'j'. So isn't it simple.