Tuesday, 4 February 2014
Friday, 31 January 2014
Core Java - Start it Now!
you need the following to start with java :
1. Text Editor
1. Text Editor
- Note Pad++ is a good Text Editor and supports other languages also.
Download NotePad++
- GEdit is another another Text Editor for Linux.
Download GEdit
Note: you can use any other Text Editor, e.g. Notepad, you are comfortable with.
2. JDK (Java Development Kit)
Get JDK 1.6
OR
Download the complete solution i.e. Java 6 Update 26 with NetBeans 7.0
Now, Let's start with Core Java: A Simple Program, shows "This is my first java program".
Open your text editor and write the given lines of Code:
class MyClass
{
public static void main(String args[])
{
System.out.println("This is my first java program");
}
}
Save your file as "MyClass.java" exactly to folder "bin" (find "bin" in the installation directory, you provide at the time of installation of jdk). Consider the class name in the code above i.e. "MyClass" which contains the main function. The program is executed by calling main(). So, the name of the file should be the name of the class containing main() and the extension must be .java otherwise you'll not be able to run the program.One more thing, Java is case sensitive, the class name "MyClass" is not similar to "myclass", "MYCLASS", Myclass, etc.
Open Command Prompt
Start Menu >> Run. Type "cmd" and press enter.
Go to "bin" directory and compile the program by executing the Java compiler "javac" as shown in the following image:
Compiler creates a "MyClass.class" which contains the bytecode version of the program. You can find "MyClass.class" in the "bin" folder
Now, to run the program, use Java application launcher "java" and pass the name of class "MyClass" as command line argument, as shown in the following image
You can see the output of the program in the image above.
Why, save the file in "bin" directory
Now, you know that you must use Java complier (javac) and Java application launcher (java) to run a program. These both files are resided in the bin folder, so that, we need to save the .java file to the bin directory.
What to do, if don't save file in "bin" directory
Yes, you can save your file anywhere in the storage area, but you need to set path to the bin directory as shown in the following image
Consider the image above, I save "MyClass.java" file to "d:\java", so I need to set the path to the "bin" directory which is resided in "c:\java\jdk1.6", so I used the following command to set the path
>>set path=%path%;c:\java\jdk1.6\bin;.;
OR, you can set path permanently to run the program whether it is saved in any directory. To set path permanently in windows, follow the steps given below:
- Right-click on My Computer
- Select Properties
- Click on Advanced Tab
- Press Environment Variables
- Select "Path" from the list, under "System variables"
- Press Edit
- Go to the end of "Variable value", insert a semicolon (;) to separate the path and write the path to "bin", for e.g. "c:\program files\jdk1.6.26\bin"
- Press OK.
Running the same program in NetBeans 7
Open NetBeans -> File Menu -> New Project
Choose Java and Java Application under Categories and Projects respectively and press Next button
Now, give the project name and location and press Finish button, you'll see that a class "MyClassNetBeans" containing the main() is created. You just insert a line of code i.e. "System.out.println("This is my first java program");" in the main(), as shown in the following image:
Press "F6" to run the program.
Output:
I hope that you have chosen a solution (either Text Editor & JDK or NetBeans with JDK) to start with Core Java.
Logger in Java - A Basic Introduction
Introduction:
A Logger is a part and parcel of any application that helps in debugging and resolving issues. There are various kinds of logger messages through which we can identify the information flowing in the system. In case of Java there are many third-party frameworks that provide flexible ways to log the required messages in the application. It is always important to know why, how and what to log. In this small article I will familiarize you with the logger API already available in Java called JDK Logger and very few people are aware of the JDK logger API. It is a common practice in case of any project to use an external logging library to track the log messages. In this small article I will present how to log the messages and how to customize the logger for our requirements easily without using any external framework.
Technicalities
There are numerous logger implementations available in the market that can be easily plugged into the system. Some of the popular logger APIs are given below.
- Commons-logging
- Jboss-logging
- Log4j
- Log4j2
- Slf4j
The basic question that always haunts us is why to use one instead of "System.out.println". Can't we customize the "println" statement available in Java? Of course we can customize it as needed, but again does it serve the purposes of our logging? I provide below the following important reasons for which we use a logger in our application.
- Easy configuration of Logger statements
- Logging messages using various formats like text, html, XML and so on
- Various types of logging persistence
- Asynchronous logger
- Categorization of logging the messages
- Backup of log message and sending to various channels
In most cases, it is observed that a novice developer always prefers to write "System.out.println()" for debugging purposes. But that creates substantial overhead when the application is moved into production. It is also observed that most of developers are happy if their log messages appear only in the console. It is always important to maintain all log messages in the file system for further analysis. Basically it provides you comprehensive diagnostic information about the various operations performed in the application. In case of post-production issues, the log file from the application helps to a greater extent to fix the issues. However let us learn a few things about the Java logging API. It is always recommended to use the logger instead of "System.out.println" even if you do not have external logging APIs.
The JDK logger comes with the package java.util. Let us have a glance at the following significant classes and interfaces available as a part of logger implementation in Java.
The JDK logger comes with the package java.util. Let us have a glance at the following significant classes and interfaces available as a part of logger implementation in Java.
- java.util.logging.Logger
- java.util.logging.Level
- java.util.logging.LogManager
- java.util.logging.Filter
java.util.logging.Logger
This class is the actual implementation of a logger framework in Java. It provides various convenient methods to log the messages. It also provides methods to plug in the handler implementation. Handlers log messages, either in the file system or in the pre-defined console. The Logger class also provides various message levels. Message levels allow prioritization of the messages to the log. The levels can be a warning, error or a simple information.
java.util.logging.Level
As I have already explained about the Level, it is a way to construct the log messages as needed. It is also important to not provide a log message after every statement. The Level class provides the following Level constants, from the Java docs.
java.util.logging.Level
As I have already explained about the Level, it is a way to construct the log messages as needed. It is also important to not provide a log message after every statement. The Level class provides the following Level constants, from the Java docs.
- SEVERE (highest value)
- WARNING
- INFO
- CONFIG
- FINE
- FINER
- FINEST (lowest value)
java.util.logging.LogManager
Java also supports logger configuration through a properties file and a LogManager class that helps to configure the config file and the one-time configuration and subsequent changes have no impact after LogManger initialization.
java.util.logging.Filter
The Filter interface provides a flexible structure to control your log messages. Let us consider a typical situation where you are dependent on other APIs and you do not want to display the messages coming from other APIs. In this situation you can customize the Java logger using a filter so that messages coming from other APIs will not be displayed or logged. Let us consider the following code snippet for the implementation of the Filter interface.
package com.ddlab.logger.custom.filter;
import java.util.logging.Filter;
import java.util.logging.LogRecord;
/**
* This class is used as a log filter. You need to provide your own implementation
* for custom logging message. In this class I have provided implementation to skip
* the log messages coming from a specific library.
* @author <a href="mailto:debadatta.mishra@gmail.com">Debadatta Mishra</a>
* @since 2013
*/
public class LogFilter implements Filter {
/**
* This method is used to provide the custom implementation for the logging
* messages. In this case the implementation prevents to log the messages coming
* from a third-party.
* @param record
* @return true or false
*/
@Override
public boolean isLoggable(LogRecord record) {
if(record.getSourceClassName().indexOf("org.some.third") != -1)
return false;
else
return true;
}
}
In this above case, we are just filtering out the messages from other APIs.
Let us consider a typical Java code where we use a JDK logger.
public class Test1 {
/**
* Java logger
*/
protected final static Logger logger = Logger.getLogger(Test1.class.getName());
static {
try {
Handler handler = new FileHandler("applogs1.log", true);
//Default is XMl Formatter
//handler.setFormatter( new java.util.logging.SimpleFormatter());
logger.addHandler(handler);
} catch (IOException ex) {
Logger.getLogger(Test1.class.getName()).log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
Logger.getLogger(Test1.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Main method
* @param args
*/
public static void main(String[] args) {
logger.log(Level.INFO, "Info Message");
logger.log(Level.SEVERE, "It is an Exception or an Error");
}}
Configuration in Java Logger
As I have already explained, Java supports logger configuration through a properties file. Let us see the sample structure of the properties file.
handlers = java.util.logging.FileHandler,java.util.logging.ConsoleHandler
java.util.logging.FileHandler.level = ALL
java.util.logging.FileHandler.encoding =
java.util.logging.FileHandler.limit =
java.util.logging.FileHandler.append = true
java.util.logging.FileHandler.pattern = logs/log%u.%g.txt
java.util.logging.ConsoleHandler.level = ALL
Java also supports logger configuration through a properties file and a LogManager class that helps to configure the config file and the one-time configuration and subsequent changes have no impact after LogManger initialization.
java.util.logging.Filter
The Filter interface provides a flexible structure to control your log messages. Let us consider a typical situation where you are dependent on other APIs and you do not want to display the messages coming from other APIs. In this situation you can customize the Java logger using a filter so that messages coming from other APIs will not be displayed or logged. Let us consider the following code snippet for the implementation of the Filter interface.
package com.ddlab.logger.custom.filter;
import java.util.logging.Filter;
import java.util.logging.LogRecord;
/**
* This class is used as a log filter. You need to provide your own implementation
* for custom logging message. In this class I have provided implementation to skip
* the log messages coming from a specific library.
* @author <a href="mailto:debadatta.mishra@gmail.com">Debadatta Mishra</a>
* @since 2013
*/
public class LogFilter implements Filter {
/**
* This method is used to provide the custom implementation for the logging
* messages. In this case the implementation prevents to log the messages coming
* from a third-party.
* @param record
* @return true or false
*/
@Override
public boolean isLoggable(LogRecord record) {
if(record.getSourceClassName().indexOf("org.some.third") != -1)
return false;
else
return true;
}
}
In this above case, we are just filtering out the messages from other APIs.
Let us consider a typical Java code where we use a JDK logger.
public class Test1 {
/**
* Java logger
*/
protected final static Logger logger = Logger.getLogger(Test1.class.getName());
static {
try {
Handler handler = new FileHandler("applogs1.log", true);
//Default is XMl Formatter
//handler.setFormatter( new java.util.logging.SimpleFormatter());
logger.addHandler(handler);
} catch (IOException ex) {
Logger.getLogger(Test1.class.getName()).log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
Logger.getLogger(Test1.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Main method
* @param args
*/
public static void main(String[] args) {
logger.log(Level.INFO, "Info Message");
logger.log(Level.SEVERE, "It is an Exception or an Error");
}}
Configuration in Java Logger
As I have already explained, Java supports logger configuration through a properties file. Let us see the sample structure of the properties file.
handlers = java.util.logging.FileHandler,java.util.logging.ConsoleHandler
java.util.logging.FileHandler.level = ALL
java.util.logging.FileHandler.encoding =
java.util.logging.FileHandler.limit =
java.util.logging.FileHandler.append = true
java.util.logging.FileHandler.pattern = logs/log%u.%g.txt
java.util.logging.ConsoleHandler.level = ALL
The following Java code is used to configure the logger config.
private static LogManager manager = LogManager.getLogManager();
static {
//Initialize the logger config file.
try {
InputStream in = new FileInputStream("logconfig/logconfig.properties");
manager.readConfiguration(in);
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Configuration
You can download the complete project on Java logger usage from this site or from the dropbox link "https://www.dropbox.com/s/qevu7xo05b01i61/javalogger.zip". You can configure the project in Eclipse or Netbeans IDE. Run the test classes available inside the test source folder.
private static LogManager manager = LogManager.getLogManager();
static {
//Initialize the logger config file.
try {
InputStream in = new FileInputStream("logconfig/logconfig.properties");
manager.readConfiguration(in);
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Configuration
You can download the complete project on Java logger usage from this site or from the dropbox link "https://www.dropbox.com/s/qevu7xo05b01i61/javalogger.zip". You can configure the project in Eclipse or Netbeans IDE. Run the test classes available inside the test source folder.
Java: Armstrong, Palindrome & Prime Numbers
Before beginning to write code, you should know what these numbers are. So, let's start with a little introduction into these numbers.
Armstrong Number
A number is called Armstrong Number, if the sum of its digits to the power of number of digits is number itself. For example,
we have a number, 1634. To determine whether 1634 is an Armstrong, we need to check:
Does 14 + 64 + 34 + 44 equal 1634 ?
Yes! So 1634 is Armstrong Number.
Similarly, 153 is Armstrong because 13 + 53 + 33 equals to 153.
Palindrome Number
A number is said to be a Palindrome, if the reverse of its digit is number itself. For eg. 121, 959, 1441, etc.
Prime Number
A natural number greater than 1 is called a Prime Number, if it has no divisor other than 1 and itself. For eg. 2, 3, 5, 7, ...
The Java program written below has a class named VariousNumbers which contain three public static functions excluding main, listed below:
1. public static boolean Armstrong(int) // Return true, if an integer is found to be an Armstrong, else return false.
2. public static boolean Palindrome(int) // Return true, if an integer is found to be a Palindrome, else return false.
3. public static boolean Prime(int) // Return true, if an integer is found to be a Prime, else return false.
Code
public class VariousNumbers {
public static void main(String[] args) {
System.out.println("Armstrong Numbers 1 to 10000 >>");
for (int i = 1; i <= 10000; i++) {
if (Armstrong(i) == true) {
System.out.print(i + " ");
}
}
System.out.println("\nPalindrome Numbers 100 to 300 >>");
for (int i = 100; i <= 300; i++) {
if (Palindrome(i) == true) {
System.out.print(i + " ");
}
}
System.out.println("\nPrime Numbers up to 100 >>");
for (int i = 1; i <= 100; i++) {
if (Prime(i) == true) {
System.out.print(i + " ");
}
}
}
public static boolean Armstrong(int num) {
int num1 = num;
/* Converting Integer to String. It'll help to find number of
digits in the Integer by using length() */ String str = Integer.toString(num);
int rem;
int result = 0;
while (num > 0) {
rem = num % 10;
num = num / 10;
result = result + ((int) Math.pow(rem, str.length()));
}
if (result == num1) {
return true;
} else {
return false;
}
}
public static boolean Palindrome(int num) {
int num1 = num;
int rem;
int result = 0;
while (num > 0) {
rem = num % 10;
num = num / 10;
result = (result + rem) * 10;
}
result /= 10;
if (result == num1) {
return true;
} else {
return false;
}
}
public static boolean Prime(int num) {
if (num < 2) {
return false;
}
int div = num / 2;
for (int i = 2; i <= div; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
}
public static void main(String[] args) {
System.out.println("Armstrong Numbers 1 to 10000 >>");
for (int i = 1; i <= 10000; i++) {
if (Armstrong(i) == true) {
System.out.print(i + " ");
}
}
System.out.println("\nPalindrome Numbers 100 to 300 >>");
for (int i = 100; i <= 300; i++) {
if (Palindrome(i) == true) {
System.out.print(i + " ");
}
}
System.out.println("\nPrime Numbers up to 100 >>");
for (int i = 1; i <= 100; i++) {
if (Prime(i) == true) {
System.out.print(i + " ");
}
}
}
public static boolean Armstrong(int num) {
int num1 = num;
/* Converting Integer to String. It'll help to find number of
digits in the Integer by using length() */ String str = Integer.toString(num);
int rem;
int result = 0;
while (num > 0) {
rem = num % 10;
num = num / 10;
result = result + ((int) Math.pow(rem, str.length()));
}
if (result == num1) {
return true;
} else {
return false;
}
}
public static boolean Palindrome(int num) {
int num1 = num;
int rem;
int result = 0;
while (num > 0) {
rem = num % 10;
num = num / 10;
result = (result + rem) * 10;
}
result /= 10;
if (result == num1) {
return true;
} else {
return false;
}
}
public static boolean Prime(int num) {
if (num < 2) {
return false;
}
int div = num / 2;
for (int i = 2; i <= div; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
}
Output
Armstrong Numbers 1 to 10000 >>
1 2 3 4 5 6 7 8 9 153 370 371 407 1634 8208 9474
Palindrome Numbers 100 to 300 >>
101 111 121 131 141 151 161 171 181 191 202 212 222 232 242 252 262 272 282 292
Prime Numbers up to 100 >>
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
1 2 3 4 5 6 7 8 9 153 370 371 407 1634 8208 9474
Palindrome Numbers 100 to 300 >>
101 111 121 131 141 151 161 171 181 191 202 212 222 232 242 252 262 272 282 292
Prime Numbers up to 100 >>
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Thursday, 30 January 2014
print duplicate number
how can write java program for print this array {1,1,2,5,7,7,8,0,9,9};
Duplicate number????
Answer:int[] numbers = { 1, 5, 23, 2, 1, 6, 3, 1, 8, 12, 3 };
Arrays.sort(numbers);
for(int i = 1; i < numbers.length; i++) {
if(numbers[i] == numbers[i - 1]) {
System.out.println("Duplicate: " + numbers[i]);
}
}
Duplicate number????
Answer:int[] numbers = { 1, 5, 23, 2, 1, 6, 3, 1, 8, 12, 3 };
Arrays.sort(numbers);
for(int i = 1; i < numbers.length; i++) {
if(numbers[i] == numbers[i - 1]) {
System.out.println("Duplicate: " + numbers[i]);
}
}
Tuesday, 28 January 2014
Introduction to Jdbc
It is a technique through which we connect our program to the database smoothly. Java is one of the best languages that provides a connection through to the database smoothly, in comparison to other language.
| Java Program ||--->JDBC Api ||--->Driver||--->||Database Source |
Figure 1: Description of the working of Jdbc
Steps of Jdbc for connecting the database
- Loading the Jdbc driver.
- Connection to the Dbms.
- Creating and executing a statement.
- Processing data returned by the Dbms
- Close the connection with the Dbms.
We have to import the sql package, which resides in the java .lang package for performing these steps. After this step we have to write our code for connecting to any database.
- Loading Jdbc Driver: In this step, we load the driver class at runtime which implements theDriver interface. In Java we use a class known as Class for loading any class at runtime .forName(Driver name in String) is the static method of class, Class is used to load any driver class at runtime. The return type of this method is an object of class ,Class.
- Connection to the Dbms: In the second step we have to create a connection with the database. For this we use the DriverManagerclass. There is a static method,getConnection("url","user name","password") of DriverManager class.It takes three string type arguments,and returns object of Connection.Syntax: Connection con = DriverManager.getConnection("jdbc:odbc:mydsn","system","tiger");
- Creating and executing a statement: Using a Connection we create statement by the method createStatement() and get the object of Statement.Syntax:Statement s=con.createStatement();
- Processing data returned by Dbms: According to our query we use the data returned by Dbms.
Syntax:Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
The above line is used for loading any driver class at runtime. We generally do not catch the value (Object of class,Class) returned by this method.
The above line is used for loading any driver class at runtime. We generally do not catch the value (Object of class,Class) returned by this method.
Simple program for creating connection in Java
import java.sql.*;
class CreateConnection
{
public static void main(String s[])
{
try
{
//Loading the Driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//Creating the Connection
Connection con = DriverManager.getConnection("jdbc:odbc:mydsn","System","tiger");
if(con!=null)
{
System.out.println("Connection Successfull");
}
else
{
System.out.println("Connection could not be established");
}
//closing the connection
conn.close();
}
catch(SqlException e)
{
System.out.println("Exception occured"+ e);
}
}
}
class CreateConnection
{
public static void main(String s[])
{
try
{
//Loading the Driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//Creating the Connection
Connection con = DriverManager.getConnection("jdbc:odbc:mydsn","System","tiger");
if(con!=null)
{
System.out.println("Connection Successfull");
}
else
{
System.out.println("Connection could not be established");
}
//closing the connection
conn.close();
}
catch(SqlException e)
{
System.out.println("Exception occured"+ e);
}
}
}
After compilation and execution of above program we get the output as:

Subscribe to:
Posts (Atom)

