Java Generating Prime Number

/*
This class check the prime number between 1 to 1000 and write the prime number.
*/

public class PrimeNumber
{
// This method tests whether a given number is prime or not.
public static boolean isPrime ( int num )
{
boolean prime = true;
int limit = (int) Math.sqrt ( num );

for ( int i = 2; i <= limit; i++ )
{
if ( num % i == 0 )
{
prime = false;
break;
}
}

return prime;
}

public static void main ( String[] args )
{
// This loop writes out all the prime numbers less than 1000.
for ( int i = 2; i <= 1000; i++ )
{
if ( isPrime ( i ) )
System.out.println ( i );
}
}
}

Java JDBC with using Oracle


The JDBC is used whenever a Java application should communicate with a relational database for which a JDBC driver exists. JDBC is part of the Java platform standard; all visible classes and interfaces used in the JDBC are placed in package Java

Main JDBC classes:

Download the Java connecting with Oracle Code, you have to oracle jdbc driver jar file in your project library reference or in your classpath so that you compiler can find the oracle jdbc jar file….

MyOracle.java  oracle-java-jdbc-driver.jar

  • DriverManager. Manages a list of database drivers. Matches connection requests from the java application with the proper database driver using communication subprotocol. The first driver that recognizes a certain subprotocol under jdbc will be used to establish a database Connection.
  • Driver. The database communications link, handling all communication with the database. Normally, once the driver is loaded, the developer need not call it explicitly.
  • Connection. Interface with all methods for contacting a database
  • Statement. Encapsulates an SQL statement which is passed to the database to be parsed, compiled, planned and executed.
  • ResultSet. The answer/result from a statement. A ResultSet is a 2D list which encapsulates all outgoing results from a given SQL query.

Continue Reading…

Java creating custom Exceptions

Java supports the custom, user defined exception. Java provides the well known and common exception classes and gives freedom for developer to create their own exception classes matching to their specific business logic/role. For example, a user not found exception would be implemented by its own.

Download the Java Source code  for creating user custom exceptions

MyException.java  UserException.java

Continue Reading…

Java Object Serialization by using Java I/O Streams

The task is to store different objects of classes in a physically located file on hard disk. For this to store objects and their states (including the values of their data members) we have to make those classes serializeable. Use Standard Java I/O streams FileOutputStream, ObjectOutputStream to write/store to file and FileInputStream, ObjectInputStream streams to read objects from the file. After reading all objects from the file, have to type caste to their original class type and then get data from these casted objects.

Following is the code that you can see and can also download. MyObjects.java

Continue Reading…

Understanding Exceptions in Java

An exception is an error that happens when an application is running. When an exception condition happens, the exception is said to be thrown, and it changes the normal execution control flow of the program. Java offers a very comprehensive and flexible system for exception handling. The main benefit of such a system is that it largely automates the process of error handling, which otherwise would need to be coded into each application: what a waste of resources that would be. All exceptions are represented by classes organized into a hierarchy tree. Let’s take a look at that tree…well, a part of it.

The Exception Tree in Java s they say, everything in Java is a class (or object), and the exceptions are no exception. They are organized into a hierarchy of classes, a part of which is shown in Figure below.

The Exception Tree in Java

Checked Exceptions and Runtime Exceptions

When in a program, if you perform an operation that causes an exception—that is, an exception is hrown—you can always catch the exception (you will see how later in the chapter) and deal with it n the code. This is called handling the exception. Based on whether or not you are required to handle hem, the exceptions in Java are classified into two categories: checked exceptions and runtime xceptions.
Checked Exceptions
This is the category of exceptions for which the compiler checks (hence the name checked exceptions) o ensure that your code is prepared for them: prepare for unwelcome but expected guests. These exceptions are the instances of the Exception class or one of its subclasses, excluding the runtime Exception subtree. Checked exceptions are generally related to how the program interacts with its environment; for example, URISyntaxException and ClassNotFoundException are checked exceptions.
The conditions that generate checked exceptions are generally outside the control of your program, and hence they can occur in a correct program. However, you can anticipate (expect) them, and thus you must write the code to deal with them. The rule is: when a checked exception is expected, either declare it in the throws clause of your method or catch it in the body of your method, or do both; i.e. you can just throw it without catching it, you can catch it and recover from it, or you can catch it and rethrow it after doing something with it. Just throwing it without catching it is also called ducking it. You will get more comfortable with the throw and catch terminology by the end of this chapter.

Runtime Exceptions
The exceptions of type RuntimeException occur due to program bugs. The programmer is not required to provide code for these exceptions because if the programming were done correctly in the first place, these exceptions wouldn’t occur, anyway. Because a runtime exception occurs as a result of incorrect code, catching the exception at runtime is not going to help, although doing so is not illegal. However, you would rather write the correct code to avoid the runtime exceptions than write the code to catch them. An exception represented by the ArithmeticException class is an example of runtime exceptions. Again, you do not need to declare or catch these exceptions.

Runtime exceptions (exceptions of type RuntimeException or its subclasses) and errors (of type Error or its subclasses) combined are also called unchecked exceptions and they are mostly thrown by the JVM, whereas the checked exceptions are mostly thrown programmatically. However, there is no rigid rule.

Composition and Aggregation using Java

There is always been confusion about composition and aggregation. While in servicing NetSol Technologies, I came to learn practically what is composition and aggregation. First thing is both are type of association.  Below is the exact definition of each term and then practical Java code, where you can understand exactly how can we implement composition and aggregation in programming.

Composition: Life time of objects got to be the same. For example there is a composition between car-frame and a car. If the car gets destroyed the car-frame would also get destroyed.

Aggregation: Life times of the objects are not the same, one object can live even after the other object has been destroyed.

How to Take Screenshots in Java

Have you ever wanted to grab a screenshot from your Java application? Here’s a quick tutorial on how to grab a screenshot and save it to a JPEG and PNG file. This shows how to use the Robot class to capture the screen image and the ImageIO API to save it as a JPG and PNG.

First, we need to determine the size of the screen and create a rectangle with the screen dimensions. We can query the toolkit to determine the size of the screen. In our example, we are grabbing the entire screen. You can also use this same method to grab the contents of a window or a specific screen rectangle.

//Get the screen size
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension screenSize = toolkit.getScreenSize();
Rectangle rect = new Rectangle(0, 0, screenSize.width, screenSize.height);

Next, you will need to create an instance of the Robot and capture the desired rectangle of the screen. The createScreenCapture() method takes a Rectangle and returns a BufferedImage.

Robot robot = new Robot();
BufferedImage image = robot.createScreenCapture(rectangle);

Finally, we are going to save the screenshot as a PNG and JPG. For this, we will use the ImageIO API to convert from a BufferedImage to a PNG and to a JPG.

//Save the screenshot as a png
file = new File(”screen.png”);
ImageIO.write(image, “png”, file);

//Save the screenshot as a jpg
file = new File(”screen.jpg”);
ImageIO.write(image, “jpg”, file);

The complete screenshot example is below:

import java.awt.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;

try
{
//Get the screen size
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension screenSize = toolkit.getScreenSize();
Rectangle rect = new Rectangle(0, 0,
screenSize.width,
screenSize.height);
Robot robot = new Robot();
BufferedImage image = robot.createScreenCapture(rect);
File file;

//Save the screenshot as a png
file = new File(”screen.png”);
ImageIO.write(image, “png”, file);

//Save the screenshot as a jpg
file = new File(”screen.jpg”);
ImageIO.write(image, “jpg”, file);
}
catch (Exception e)
{
System.out.println(e.getMessage());
}

Java Buzzwords

You will hear and see quite a few Java buzzwords in the Java world. It’s important to know the Java buzzwords because they represent the factors that have played important roles in shaping the Java language. These words are summarized in Table 1-3.

Buzzword

Description

Architecture neutral The Java compiler compiles the source code into bytecode, whichdoes not depend upon any machine architecture, but can be easilytranslated into a specific machine by a JVM for that machine.
Distributed Java offers extensive support for the distributed environment of theInternet.
Dynamic New code can be added to the libraries without affecting theapplications that are using the libraries, runtime type informationcan be found easily, and so on.
High performance The Just-In-Time (JIT) compilers improve the performance ofinterpreting the bytecode by caching the interpretations.
Interpreted The Java compiler compiles the source code into bytecode, whichcan be executed on any machine by the Java interpreter of anappropriate JVM.
Multithreaded Java provides support for multithreaded programming.
Object oriented Java supports the features and philosophy of object-orientedprogramming.
Portable There are no implementation-dependent aspects of the languagespecifications. For example, the sizes of primitive data types and thebehavior of the arithmetic on them are specified. This contributes tomaking programs portable among different platforms such asWindows, Mac, and Unix.
Robust Java provides support for error checking at various stages: earlychecking at compile time, and dynamic checking at runtime. Thiseliminates some situations that are error prone such as pointers inthe C language.
Secure Because Java supports the distributed environment of the Internet,it also offers multiple security features.
Simple Java omits many clumsy and confusing features of otherprogramming languages such as C++. Also, Java is designed to beable to run stand-alone on small machines. The size of the basicinterpreter and class support is 40 KB.

The most popular buzzwords are architecture neutral (or platform independent), object oriented, and portable.

The three most important takeaways from this chapter are the following:

  • You write a computer program in a high-level language and use the compiler to convert it into an executable program that will actually be executed by the computer.
  • Following the underlying philosophy of object-oriented programming, Java allows you to adapt computing to the problem that you are trying to solve by directly representing the objects in the problem with objects in the Java program. The objects are created from classes that you write.
  • The Java compiler creates bytecode that can be translated by a Java virtual machine (JVM) for a specific platform, such as Windows, Solaris, or Mac, into executable instructions. So, a Java program written once can be run on different platforms by using different JVMs.

The Memory Usage by a Java Program

The instructions of a running program and the related data are temporarily stored in the computer memory. Java has good news for you here: you don’t need to worry about memory management because the JVM and garbage collector will take care of it. However, you can help by being aware of where different things are stored in the memory. This will also help you to understand how objects are created. As shown in Figure 1-4, a program’s data is placed in two different areas in memory: the stack and the heap. Stack and heap refers to the different ways (or places) to store the elements of a running program in memory.

Java Memory Stack Heap

Living on the Stack

The following elements of a Java program live on the stack:

  • Local variables: The variables of primitive types defined inside a method or as method parameters.
  • Local reference variables: The variables that refer to an object and are defined inside a method or as a method parameter. Remember that an object that a local variable refers to lives on the heap and not on the stack.
  • Method invocations: When you invoke (call) a method, the method is pushed onto the stack (that is, placed on top of the stack).

Local variables live inside a method, and the scope of a local variable is the execution of the method. When the method execution is complete, the local variables inside the method are gone. But the objects, to which some of these local variables may be referring, are still alive and well on the heap.

Living on the Heap

The following elements of a Java program live on the heap:

  • Instance variables: The variables of primitive types defined inside a class but outside of all its methods.
  • Instance reference variables: The variables that refer to an object and are defined inside a class but outside of all its methods.
  • Objects: Represent the entities in the real-world problem that the Java program is trying to solve. All the objects live on the heap, always.

Remembering whether a particular element lives on the stack or on the heap is easy: a local variable (primitive or reference) belongs to a method and lives with it on the stack, while an instance variable belongs to an object and lives with it on a heap. However, also note that a local reference variable on a stack points to an object on the heap, and the object will not die with the local reference variable.

The objects on the heap that are no longer in use are eventually collected by a program called a garbage collector to free up the memory used by them. For this reason, the heaps are also called garbage-collectible heaps.

The instanceof Operator in Java

The instanceof operator determines if a given object is of the type of a specific class. To be more specific, the instanceof operator tests whether its first operand is an instance of its second operand. The test is made at runtime. The first operand is supposed to be the name of an object or an array element, and the second operand is supposed to be the name of a class, interface, or array type. The syntax is

<op1> instanceof <op2>

The result of this operation is a boolean: true or false. If an object specified by <op1> is an instance of a class specified by <op2>, the outcome of the operation is true, and otherwise is false. The outcome of the operation will also be true if <op2> specifies an interface that is implemented either by the class of the object specified by <op1> or by one of its superclasses. For example, consider the following code fragment:

interface X{}
class A implements X {}
class B extends A {}
A a = new A();
B b = new B();

Note that class B does not implement the interface X directly, but class A does, and class B extends class A. Given this code, all of the following statements are true:

if( b instanceof X)
if (b instanceof B)
if(b instance of A)
if(a instance of A)
if(a instanceof X)

Knowing the type of an object at runtime is useful for the following reasons:

  • Some invalid casts (explicit type conversions) involving class hierarchies cannot be caught at compile time. Therefore, they must be checked at runtime (using the instanceof operator), to avoid a runtime error.
  • You might have a situation where one process is generating various kinds of objects, and the other process is processing them. The other process may need to know the object type before it can properly process it. In this situation the instanceof operator would be helpful, too.