Technology

The parent category for technical blogs.

Scripting Elements in JSP (Java Server Pages)


Scripting Elements in Java Server Pages

JSP scripting elements allow you to use Java programming language statements in your JSP pages. Scripting elements are typically used to create and access objects, define methods, and manage the flow of control. Many tasks that require the use of scripts can be eliminated by using custom tag libraries, in particular the JSP Standard Tag Library. Because one of the goals of JSP technology is to separate static data from the code needed to dynamically generate content, very sparing use of JSP scripting is recommended. Nevertheless, there may be some circumstances that require its use.
1. JSP Declarations.
2. JSP Expressions.
3. JSP Scriptlets. Continue reading

Directives in JSP (Java Server Pages)


1 Comment Leave a reply                     

Directives in Java Server Pages

A directive gives further information to the JSP Container that applies to how the page is compiled. An example of this is to reference Java packages in a manner similar to the import statement.

Directives are classified in following categories:
1. Page Directive.
2. Include Directive.
3. Taglib Directive.
Continue reading

Life Cycle of JSP (Java Server Pages)


2 Comments Leave a reply                     

About Life Cycle and Uses of JSP Technology

JSP stands for Java Server Pages. It is Java Code inside HTML. It is used for View in Model-View-Controller architecture.

Using JSP, developer can generate dynamic content on web pages. It is capable to do almost all things that a Servlet can do. JSP is server side technology. Major advantage of using JSP is that it separates business logic from presentation. Business logic can be implemented in Java and dynamic presentation content is sent to client using JSP to display it on browser. Continue reading

CSS Image Sprites


Leave a reply                     

What Are CSS Sprites? Why They’re Cool? How To Use Them?

Do you really understand them? The name might be a little misleading, because sprites aren’t little images like you might be picturing, a sprite is actually one big image. Have you ever seen the CSS technique where the “on” and “off” states of a button are contained within the same image and are activated by shifting the background-position?
You may combine an unlimited number of images into one. The origin of the term “sprites” comes from old school computer graphics and the video game industry. The idea was that the computer could fetch a graphic into memory, and then only display parts of that image at a time, which was faster than having to continually fetch new images. The sprite was the big combined graphic. CSS Sprites is pretty much the exact same theory: get the image once, shift it around and only display parts of it, saves the overhead of having to fetch multiple images. Continue reading

Lazy Load WordPress Gravtar Avtar using JavaScript / JQuery


Leave a reply                     

How to Lazy load WordPress gravtar avtar in a web page using Javascript / JQuery?

A webpage load time plays a very crucial role in SEO and impacts your website ranking significantly. Google has already incorporated site speed as one of the several things that it uses to determine search ranking. The faster your website loads, the better it will perform in Google ranking. The images (specifically the alt) also make an measurable impact on Google and other search engines page ranking. In today’s IT era, the high quality images are common and it also makes better look and fell of a page, but it impacts site performance if the image is large or have multiple images on a page and if at the same time they are of high quality (resolution), they becomes larger in size and takes some time to load. it doesn’t mean you use low quality images but it means use try to make them smaller in size (again not confuse with height and width but it means number of bytes). Continue reading

Lazy Load Image using JavaScript / JQuery


2 Comments Leave a reply                     

How to Lazy load images in a web page using Javascript / JQuery?

A webpage load time plays a very crucial role in SEO and impacts your website ranking significantly. Google has already incorporated site speed as one of the several things that it uses to determine search ranking. The faster your website loads, the better it will perform in Google Ranking. The images (specifically the alt) also make an measurable impact on Google and other search engines page ranking. In today’s IT era, the high quality images are common and it also makes better look and fell of a page, but it impacts site performance if the image is large or have multiple images on a page and if at the same time they are of high quality (resolution), they becomes larger in size and takes some time to load. it doesn’t mean you use low quality images but it means use try to make them smaller in size (again not confuse with height and width but it means number of bytes). Continue reading

Google Maps Javascript API With Examples


Leave a reply                     

Introduction to Google Maps API

Google Maps API have been in top place for many years, they are in number one position consistently and till date no other Map providers like Bing, Yahoo etc are in close competition with Google Maps API. I have worked for about four years with a Vehicle Tracking System Company as Project Manager and almost daily used to have chance to see some Maps API JavaScript Code. The API is easy to understand and Use and Most Important thing i like in it is bug free, i never encountered with an error API code. If you like JavaScript believe me you will love Google Maps API. Thousand of APIs are available to customize and change look and feel on Google Map. You can describe a wide range of data using Google Maps API. The Google maps API makes places, information, roads and even search more accurate and understandable. Continue reading

CSS Rounded Corner Without Images


Leave a reply                     

How to make corners rounded?, Rounded corner CSS, Using CSS rounding corners without images

Most websites uses rounded corner tables and divs to display information on the webpage. It looks sleek and also eye appealing. Not all designers know but is possible without images in CSS3-compatible browsers. -moz and -webkit properties are used to display the round corners, they basically uses radius in corners to make it rounded. Continue reading

HTML5 JavaScript Geolocation in Browser


Leave a reply                     

The Geolocation API provides a method to locate the user’s exact position. This is useful in a number of ways like providing a user with location specific information, providing route navigation etc.

Although it’s not actually part of the HTML5 specification, as it was developed as a separate specification by the W3C.

Compatibility

Currently the W3C Geolocation API is supported by the following desktop browsers:

Continue reading

Top Best Google Page Rank


3 Comments Leave a reply                     

How did I achieve Good Google Page Rank in less time?

This was the question asked by many new bloggers.
Google Page Rank

Following are the methods which might be useful for new bloggers.

Quality & unique content:

Start blogging the contents which you are good at & knew the subject well. Keeping targeted readers in mind, list down the categories to use in the blog. start posting blogs on regular basis & follow the rule strictly. Try to maintain at least one post daily & if possible on different categories. At early days don’t worry about Ranking or making money from the blog. Having passion towards technology wanted to share my learnings with the readers. Remember If your content is good, you will get visitors which eventually increase ranking and then you can think of generating revenue.

Usefull Tips:
  • Don’t copy content or images from other sites, this may harm your ranking or may got black listed or may face legal actions.
  • Schedule Your Blog postings. New Bloggers should follow this strictly otherwise someday you might lose interest in blogging if you are not regularly posting the content. Regular content additions will make site crawling by search engines fast.
  • Don’t copy images from search engine its strictly copyright infringement.
  • Don’t worry about short content, keep writing, your writing skill improves with experience and after few days you are one of the top best blogger.

Continue reading

CSS border-left-color Property


Leave a reply                     

Definition and Usage

The border-left-color property sets the color of an element’s left border.

Default value: not specified
Version: CSS1
JavaScript syntax: object.style.borderLeftColor="blue"

Property Values

Value Description
color Specifies the color of the left border.
transparent Specifies that the border color should be transparent.
This is default
inherit Specifies that the border color should be inherited
from the parent element

Send EMail with Inline Image


Leave a reply                     

How to send HTML email with inline image in java?

Java email API example

Java email MimeMessage, MimeBodyPart, MimeMultipart, Multipart, BodyPart

Java send HTML email with inline image

MimeMessage MimeBodyPart MimeMultipart Multipart BodyPart

An Email with inner image needs image code at two places, add the image as an attachment and reference it inside an HTML body part. Continue reading

Send EMail with Attachment


Leave a reply                     

How to send HTML email with attachment in java?

Java email API example

Java email MimeMessage, MimeBodyPart, MimeMultipart, Multipart, BodyPart, FileDataSource, DataSource, DataHandler

Java send HTML email with attachment

MimeMessage MimeBodyPart MimeMultipart Multipart BodyPart FileDataSource DataSource DataHandler

package raghuwansh.java.email;

import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class SendEMailWithAttachment {

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

		// Recipient email, for multiple recipient's separate by comma
		String to = "to email id";
		// Sender email
		String from = "your email id";
		// Sender host
		String host = "localhost";
		// Get system properties
		Properties properties = System.getProperties();
		// Mail server
		properties.setProperty("mail.smtp.host", host);
		// Get the default Session object.
		Session session = Session.getDefaultInstance(properties);
		try {
			// Create a default MimeMessage object.
			MimeMessage message = new MimeMessage(session);
			// From
			message.setFrom(new InternetAddress(from));
			// To
			message.addRecipient(Message.RecipientType.TO, new InternetAddress(
					to));
			// Subject
			message.setSubject("Subject");
			// HTML message
			Multipart multipart = new MimeMultipart();
			BodyPart htmlPart = new MimeBodyPart();
			htmlPart
					.setContent(
							"<h1>Message on <strong>http://www.raghuwansh.com</strong></h1>",
							"text/html");
			htmlPart.setDisposition(BodyPart.INLINE);
			multipart.addBodyPart(htmlPart);
			// Attachment
			BodyPart attachment = new MimeBodyPart();
			DataSource source = new FileDataSource(
					"C:/raghuwansh/attachment.txt");
			attachment.setDataHandler(new DataHandler(source));
			attachment.setFileName("attachment.txt");
			multipart.addBodyPart(attachment);

			message.setContent(multipart);
			// Send message
			Transport.send(message);
			System.out.println("Sent successfully.");
		} catch (MessagingException mex) {
			mex.printStackTrace();
		}
	}
}

Select All Rows From Table


Leave a reply                     

Java MySql Select

How to Select MySql Table Data in Java?

Java MySql ResultSet

Java Select Query Using Statement

Query: SELECT columnname1, columnname2 FROM tablename
Above query selects all rows from table tablename contains data for columns columnname1 and columnname2 Continue reading

Update Table in Java


Leave a reply                     

How to Update MySql Table in Java?

Java Update Query

Update Value Using Java

Java Update Mysql Table Data

executeUpdate: This method of Statement is used for CREATE/INSERT/UPDATE/DELETE queries.
Following query used to update data
UPDATE tablename set columnname2 = ‘http://www.’ where columnname1 = ’1′
tablename the table in which values are updated.
columnname2 name of column to be changed. Continue reading

Insert Into Table


Leave a reply                     

Insert Into MySql Table in Java

Java MySql Insert

MySql Insert Table Using PreparedStatement

How to Insert Data In MySql Database Table in Java

PreparedStatement: Is used to complied once and then executed in loop to insert multiple values in database table tablename in column columnname2, columnname1 is not mentioned since it is auto_increment. Continue reading

Insert in Table


Leave a reply                     

Insert in Table in Java

MySql Insert into Table

Java Insert in MySql table

How to Insert Data in MySql Table in Java

Following INSERT statement is used to insert data “www.” in database table tablename in column columnname2, the value for column columnname1 automatically inserted since it is auto increment column.
INSERT INTO tablename(columnname2) values (‘www.’) Continue reading

Create Table


Leave a reply                     

Create Table in Java

MySql Create Table

Java Create Table

How to Create Table In MySql in Java?

Following program creates table tablename in MySql database databasename.
columnname1 and columnname2 are name of columns in table.
auto_increment is used to make column auto increment.
primary key makes columnname1 primary key.

package raghuwansh.java.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class CreateTable {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			Class.forName("com.mysql.jdbc.Driver");
			Connection connection = DriverManager.getConnection(
					"jdbc:mysql://localhost:3306/databasename", "root", "");
			Statement statement = connection.createStatement();
			statement
					.executeUpdate("CREATE TABLE tablename(columnname1 int(5) auto_increment primary key, columnname2 varchar(128))");
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
}

Create Database in Java


Leave a reply                     

Create MySql Database in Java

Create Database

How to Create New Database Using Java Program?

package raghuwansh.java;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class CreateDatabase {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			Class.forName("com.mysql.jdbc.Driver");
			Connection connection = DriverManager.getConnection(
					"jdbc:mysql://localhost:3306/career", "root", "");
			Statement statement = connection.createStatement();
			statement.executeUpdate("CREATE DATABASE databasename");
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
}

JDBC Connection


Leave a reply                     

Java Database Connection

Java MySql Connection

How to Connect with MySql Database in Java

MySql Database Connection in Java

Database Connection

Get All Table Names in Database

Connection: This interface is used to connect with database like MySql.
Class.forName(String driver): forName method loads the driver.
DriverManager: This class controls a set of JDBC drivers. Each driver has to be register with this class.
getConnection(String url, String userName, String password): This method is used to create connection with database with credentials.
DataBaseMetaData: This interface gives information about the database(data about database) like number of tables in the database, columns of the table etc. Continue reading

Current Date In Java


Leave a reply                     

Java Get Current Date

Get System Date In Java

How To Get Current Date From Calendar

package raghuwansh.java;

import java.util.Calendar;

public class CurrentDateInJava {

/**
* @param args
*/
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
int month = cal.get(Calendar.MONTH);
int year = cal.get(Calendar.YEAR);
int day = cal.get(Calendar.DAY_OF_MONTH);
System.out.println(“Current date : ” + day + “-” + (month + 1) + “-”
+ year);
}
}
/*
Output:
Current date : 18-8-2013
*/

Collection To Array


Leave a reply                     

Convert List to Array

Java Convert ArrayList to Array

Java Collection to Array

Collection to Array in Java

toArray: method in the Collection interface converts collection to array.

package raghuwansh.java;

import java.util.ArrayList;

public class ToArray {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		ArrayList<String> list = new ArrayList<String>();
		list.add("This ");
		list.add("is ");
		list.add("a ");
		list.add("example ");
		list.add("on ");
		list.add("www.raghuwansh.com.");
		String[] strFromListOne = new String[6];
		String[] strFromListTwo = list.toArray(strFromListOne);
		for (int i = 0; i < strFromListOne.length; ++i) {
			System.out.print(strFromListOne[i]);
		}
		System.out.println();
		for (int i = 0; i < strFromListTwo.length; ++i) {
			System.out.print(strFromListTwo[i]);
		}
	}

}
/*
Output:
This is a example on www.raghuwansh.com.
This is a example on www.raghuwansh.com.
*/

Compare Arrays In Java


Leave a reply                     

How to Check Two Arrays Equal or Not

Array Comparison in Java

Java Array Comparison

Java Array Equals or Not

Arrays.equals(): returns true if both arrays have same values.

package raghuwansh.java;

import java.util.Arrays;

public class CompareArrays {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		int[] arrayFirst = new int[5];
		int[] arraySecond = new int[5];

		boolean isEqual = Arrays.equals(arrayFirst, arraySecond);
		if (isEqual == false) {
			System.out.println("Arrays are not same");
		} else {
			System.out.println("Both Arrays are same");
		}

		arrayFirst[0] = 1;
		arrayFirst[1] = 2;
		arrayFirst[2] = 3;
		arrayFirst[3] = 4;
		arrayFirst[4] = 5;
		arraySecond[0] = 1;
		arraySecond[1] = 2;
		arraySecond[2] = 3;
		arraySecond[3] = 4;
		arraySecond[4] = 5;
		isEqual = Arrays.equals(arrayFirst, arraySecond);
		if (isEqual == false) {
			System.out.println("Arrays are not same");
		} else {
			System.out.println("Both Arrays are same");
		}

		arrayFirst[0] = 5;
		isEqual = Arrays.equals(arrayFirst, arraySecond);
		if (isEqual == false) {
			System.out.println("Arrays are not same");
		} else {
			System.out.println("Both Arrays are same");
		}
	}
}
/*
Output:
Both Arrays are same
Both Arrays are same
Arrays are not same
*/

Locale In Java


Leave a reply                     

List All Available Locales

Get Locale Country

Java Get Locale Language

Get Locale Display Name

The geographical location of each place is determined by Lacale Class. Each place have language, country and locale name.
Locale.getAvailableLocales(): returns Array of Locale’s.
Locale.getLanguage(): returns language code of specific Locale.
Locale.getCountry(): returns country code of specific Locale.
Locale.getDisplayName(): returns description of specific Locale.

package raghuwansh.java;

import java.util.Locale;

public class LocaleInJava {
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Locale[] locales = Locale.getAvailableLocales();
		for (int i = 0; i < locales.length; i++) {
			String language = locales[i].getLanguage();
			String country = locales[i].getCountry();
			String locale_name = locales[i].getDisplayName();
			System.out.println(i + ": " + language + ", " + country + ", "
					+ locale_name);

		}
	}
}
/*
Output:
0: ar, , Arabic
1: ar, AE, Arabic (United Arab Emirates)
2: ar, BH, Arabic (Bahrain)
3: ar, DZ, Arabic (Algeria)
4: ar, EG, Arabic (Egypt)
5: ar, IQ, Arabic (Iraq)
6: ar, JO, Arabic (Jordan)
7: ar, KW, Arabic (Kuwait)
8: ar, LB, Arabic (Lebanon)
9: ar, LY, Arabic (Libya)
10: ar, MA, Arabic (Morocco)
11: ar, OM, Arabic (Oman)
12: ar, QA, Arabic (Qatar)
13: ar, SA, Arabic (Saudi Arabia)
14: ar, SD, Arabic (Sudan)
15: ar, SY, Arabic (Syria)
16: ar, TN, Arabic (Tunisia)
17: ar, YE, Arabic (Yemen)
18: hi, IN, Hindi (India)
19: iw, , Hebrew
20: iw, IL, Hebrew (Israel)
21: ja, , Japanese
22: ja, JP, Japanese (Japan)
23: ko, , Korean
24: ko, KR, Korean (South Korea)
25: th, , Thai
26: th, TH, Thai (Thailand)
27: th, TH, Thai (Thailand,TH)
28: vi, , Vietnamese
29: vi, VN, Vietnamese (Vietnam)
30: zh, , Chinese
31: zh, CN, Chinese (China)
32: zh, HK, Chinese (Hong Kong)
33: zh, TW, Chinese (Taiwan)
34: be, , Belarusian
35: be, BY, Belarusian (Belarus)
36: bg, , Bulgarian
37: bg, BG, Bulgarian (Bulgaria)
38: ca, , Catalan
39: ca, ES, Catalan (Spain)
40: cs, , Czech
41: cs, CZ, Czech (Czech Republic)
42: da, , Danish
43: da, DK, Danish (Denmark)
44: de, , German
45: de, AT, German (Austria)
46: de, CH, German (Switzerland)
47: de, DE, German (Germany)
48: de, LU, German (Luxembourg)
49: el, , Greek
50: el, GR, Greek (Greece)
51: en, AU, English (Australia)
52: en, CA, English (Canada)
53: en, GB, English (United Kingdom)
54: en, IE, English (Ireland)
55: en, IN, English (India)
56: en, NZ, English (New Zealand)
57: en, ZA, English (South Africa)
58: es, , Spanish
59: es, AR, Spanish (Argentina)
60: es, BO, Spanish (Bolivia)
61: es, CL, Spanish (Chile)
62: es, CO, Spanish (Colombia)
63: es, CR, Spanish (Costa Rica)
64: es, DO, Spanish (Dominican Republic)
65: es, EC, Spanish (Ecuador)
66: es, ES, Spanish (Spain)
67: es, GT, Spanish (Guatemala)
68: es, HN, Spanish (Honduras)
69: es, MX, Spanish (Mexico)
70: es, NI, Spanish (Nicaragua)
71: es, PA, Spanish (Panama)
72: es, PE, Spanish (Peru)
73: es, PR, Spanish (Puerto Rico)
74: es, PY, Spanish (Paraguay)
75: es, SV, Spanish (El Salvador)
76: es, UY, Spanish (Uruguay)
77: es, VE, Spanish (Venezuela)
78: et, , Estonian
79: et, EE, Estonian (Estonia)
80: fi, , Finnish
81: fi, FI, Finnish (Finland)
82: fr, , French
83: fr, BE, French (Belgium)
84: fr, CA, French (Canada)
85: fr, CH, French (Switzerland)
86: fr, FR, French (France)
87: fr, LU, French (Luxembourg)
88: hr, , Croatian
89: hr, HR, Croatian (Croatia)
90: hu, , Hungarian
91: hu, HU, Hungarian (Hungary)
92: is, , Icelandic
93: is, IS, Icelandic (Iceland)
94: it, , Italian
95: it, CH, Italian (Switzerland)
96: it, IT, Italian (Italy)
97: lt, , Lithuanian
98: lt, LT, Lithuanian (Lithuania)
99: lv, , Latvian
100: lv, LV, Latvian (Latvia)
101: mk, , Macedonian
102: mk, MK, Macedonian (Macedonia)
103: nl, , Dutch
104: nl, BE, Dutch (Belgium)
105: nl, NL, Dutch (Netherlands)
106: no, , Norwegian
107: no, NO, Norwegian (Norway)
108: no, NO, Norwegian (Norway,Nynorsk)
109: pl, , Polish
110: pl, PL, Polish (Poland)
111: pt, , Portuguese
112: pt, BR, Portuguese (Brazil)
113: pt, PT, Portuguese (Portugal)
114: ro, , Romanian
115: ro, RO, Romanian (Romania)
116: ru, , Russian
117: ru, RU, Russian (Russia)
118: sk, , Slovak
119: sk, SK, Slovak (Slovakia)
120: sl, , Slovenian
121: sl, SI, Slovenian (Slovenia)
122: sq, , Albanian
123: sq, AL, Albanian (Albania)
124: sv, , Swedish
125: sv, SE, Swedish (Sweden)
126: tr, , Turkish
127: tr, TR, Turkish (Turkey)
128: uk, , Ukrainian
129: uk, UA, Ukrainian (Ukraine)
130: en, US, English (United States)
131: en, , English
*/

Split String


Leave a reply                     

Java split String

Java Split String In To Words

Split String In Java

Split String In To Words Java

String.split

The split method of String Class is used to Split the source String into Array of Strings.
The argument in the split method is a regular expression.

package raghuwansh.java;

public class SplitString {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String[] token = "the string to break into words".split(" ");
		for(int idx=0;idx<token.length;idx++) {
			System.out.println(token[idx]);
		}
	}
}
/*
Output:
the
string
to
break
into
words
*/

Break String InTo Words


Leave a reply                     

Break String In java

Break String In To Tokens

Java Break String

Java StringTokenizer

StringTokenizer

The StringTokenizer Class method is used to Break the source String into Tokens.
The hasMoreTokens returns true if there is more element in token.
The nextToken returns next token. Continue reading

Generate Random Number


Leave a reply                     

How to Generate Random Number in Java

Java Random Number

Random Number Generator

Random.nextInt

The Random Class generates random numbers of type int.
If a number is passed, the generated number is in range 0 and that number otherwise any number of type int is generated.

package raghuwansh.java;

import java.util.Random;

public class GenerateRandomNumber {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Random random = new Random();
		System.out.println("Generated Random Number between 0 to 100: "
				+ random.nextInt(10));
		System.out.println("Generated Random Number without range: "
				+ random.nextInt());
	}
}
/*
Output: 
Generated Random Number between 0 to 100: 6 
Generated Random Number without range: 1146131283
*/

String substring Two


Leave a reply                     

The substring(int beginIndex, int endIndex) method in the String Class returns string that is substring of source String.

package raghuwansh.java;

public class StringSubStringTwo {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
			  String str = "raghuwansh";
			  String substring = str.substring(5,7); 
			  System.out.println(substring);
		}
}
/*
Output:
wa
*/

String substring


Leave a reply                     

Java String.substring

Java substring

String.substring

substring In Java

The substring(int beginIndex) method in the String Class returns string that is substring of source String.

package raghuwansh.java;

public class StringSubStringOne {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
			  String str = "raghuwansh";
			  String substring = str.substring(5); 
			  System.out.println(substring);
		}
}
/*
Output:
wansh
*/

String Count Vowels


Leave a reply                     

Java Count Characters

Java Get Character In String

Java Vowels Counting

String.charAt

Counting the vowels in given String using charAt method of String Class.

package raghuwansh.java;

public class StringCountVowels {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String text = "the test string for vowels counting";
		int count = 0;
		for (int i = 0; i < text.length(); i++) {
			char c = text.charAt(i);
			if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
				count++;
			}
		}
		System.out.println("There are " + count + " vowels");
	}
}
/*
Output:
There are 9 vowels
*/

String charAt


Leave a reply                     

charAt in Java

Java charAt

Java String.charAt

String.charAt

The charAt method in the String Class returns Character at given index.

package raghuwansh.java;

public class StringCharAt {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String text = "the test string for charAt";
		System.out.println(text.charAt(1));
	}
}
/*
Output:
h
*/

String lastIndexOf


Leave a reply                     

Java lastIndexOf

Java String.lastIndexOf

lastIndexOf in Java

String.lastIndexOf

The lastIndexOf method in String Class returns last index of given String/Character in source String.

package raghuwansh.java;

public class StringLastIndexOf {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
			  String str = "raghuwansh.com";
			  int index = str.lastIndexOf('a'); 
			  System.out.println(index);
	}
}
/*
Output:
6
*/

String IndexOf


Leave a reply                     

indexOf Method

Java indexOf

Java String.indexOf

String.indexOf

The IndexOf method in String Class returns first index of given String/Character in source String.

package raghuwansh.java;

public class StringIndexOf {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
			  String str = "raghuwansh.com";
			  int index = str.indexOf('a'); 
			  System.out.println(index);
	}
}
/*
Output:
1
*/

Compare Strings


Leave a reply                     

Compare Strings In Java

Difference Equals Method And Operator

Difference Equals Method And Operator In Java

Java Compare Strings

Java Difference Equals Method And Operator

Java String Comparison

If two String variables point to the same object then these two variables are called references of the same object.
If two variables refers the same object then this operator == returns true otherwise false. It compares the references the two strings are pointing to rather than comparing the content of the string. If two variables have same content then equals method returns true otherwise false. It compares the content of the two strings.

package raghuwansh.java;

public class CompareString {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String string_one = "Hi";
		String string_two = "Hi";
		String string_three = new String( "Hi" );
		if (string_one == string_two) {
			System.out.println("The strings string_one and string_two are equal with ==");
		} else {
			System.out.println("The strings string_one and string_two are unequal with ==");
		}
		if (string_one == string_three) {
			System.out.println("The strings string_one and string_three are equal with ==");
		} else {
			System.out.println("The strings string_one and string_three are unequal with ==");
		}
		if (string_one.equals(string_two)) {
			System.out.println("The strings string_one and string_two are equal with equals");
		} else {
			System.out.println("The strings string_one and string_two are unequal with equals");
		}
		if (string_one.equals(string_three)) {
			System.out.println("The strings string_one and string_three are equal with equals");
		} else {
			System.out.println("The strings string_one and string_three are unequal with equals");
		}
	}
}
/*
Output:

The strings string_one and string_two are equal with ==
The strings string_one and string_three are unequal with ==
The strings string_one and string_two are equal with equals
The strings string_one and string_three are equal with equals
*/

Read Data From URL


1 Comment Leave a reply                     

How To Read URL Data?

Java Raed URL

Java Read Data From URL

Java Read URL Data

Read Data From URL In Java

Read URL Data In Java

package raghuwansh.java;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public final class ReadDataFromURL {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			URL url = new URL("http://www.raghuwansh.com");
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			connection.setConnectTimeout(10000);// 10 seconds
			connection.setReadTimeout(50000);// 50 seconds
			connection.setDoOutput(true);
			connection.setInstanceFollowRedirects(false);
			connection.setRequestMethod("GET");
			connection
					.setRequestProperty(
							"User-Agent",
							"Mozilla/5.0 (X11; U; Linux x86_64; en-GB; rv:1.8.1.6) Gecko/20070723 Iceweasel/2.0.0.6 (Debian-2.0.0.6-0etch1)");
			// change the user agent, this is only for example
			connection.setRequestProperty("Content-Type", "text/plain");
			connection.setRequestProperty("charset", "utf-8");
			connection.setUseCaches(false);

			InputStream is = connection.getInputStream();
			int i = -1;
			char c;
			StringBuffer sb = new StringBuffer();

			while ((i = is.read()) != -1) {
				// converts integer to character
				c = (char) i;
				sb.append(c);
			}
			System.out.println(sb.toString());
			connection.disconnect();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}

Difference between HashMap and HashTable


Leave a reply                     

Difference between HashTable and HashMap

HashMap

HashMap vs HashTable

HashTable

HashTable vs HashMap

Java HashMap

Java HashTable

HashMap HashTable
HashMap is part of Java Collections Framework HashTable is a legacy class and not part of Java Collections Framework
HashMap is not synchronized HashTable is synchronized
HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones HashTable better for multi-threaded applications
Iterator in the HashMap is fail-safe The enumerator for the Hashtable is not fail-safe
HashMap allows one null key and any number of null values Hashtable does not allow null keys or values

Difference between ArrayList and Vector


Leave a reply                     

ArrayList

ArrayList vs Vector

Difference between Vector and ArrayList

Java ArrayList

Java VectorX Vector

Vector vs ArrayList

ArrayList Vector
ArrayList is part of Java Collections Framework Vector is a legacy class and not part of Java Collections Framework
ArrayList is not synchronized Vector is synchronized
ArrayList better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones Vector better for multi-threaded applications
ArrayList increases its array size by 50 percent Vector defaults to doubling the size of its array
ArrayList is comparativly fast since no synchronization Vector is comparativly slow because of synchronization

Read File In Java


Leave a reply                     

How to Read File In Java

Java BufferedReader

Java FileReader

Java Read File

Read File

package raghuwansh.java;

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

public class ReadFile {
	public static void main(String args[]) {
		BufferedReader br = null;
		try {
			br = new BufferedReader(
					new FileReader(
							"C:/workspaceeclipse/raghuwansh/src/raghuwansh/java/file.txt"));
			StringBuilder sb = new StringBuilder();// complete file in string
													// buffer
			String line = null;// current line if you wnat to do something with
								// single line
			while ((line = br.readLine()) != null) {
				sb.append(line);
				sb.append("\n");
			}
			System.out.println(sb.toString());
		} catch (FileNotFoundException fileNotFoundException) {
			fileNotFoundException.printStackTrace();
		} catch (IOException iOException) {
			iOException.printStackTrace();
		} finally {
			try {
				br.close();
			} catch (IOException iOException) {
				iOException.printStackTrace();
			}
		}
	}
}

Difference between Abstract Class and Interface


Leave a reply                     

Abstract Class vs Interface

Difference between Interface and Abstract Class

Interface vs Abstract Class

Java Abstract Class and Interface

Java Interface and Abstract Class

Interface Abstract Class
Methods of a Java interface are implicitly abstract, so no implementations are there Java abstract class can have both abstract as well as instance methods with implementations
Member variables in a Java interface is by default final, so no non-final member variables are allowed An abstract class may contain non-final member variables
A Java interface can extend another Java interface only An abstract class can extend another Java class and can implement multiple Java interfaces
Member variables as well as member methods of a Java interface are public by default A Java abstract class can have non public Member variables as well as member methods
Java interface is not extended but implemented by “implements” keyword A Java abstract class is extended by “extends” keyword

Interface


Leave a reply                     

Define Interface

Java Example Interface

Java Interface

What is Interface?

An interface is a collection of abstract methods. If all methods of an interface are not implemented by a Java class then Java class must be abstract.

Example:

public interface InterfaceName {
	public final int increment = 1;
	public final int decrement = 1;
	public int getPlus(int value);
	public int getMinus(int value);
}

InterfaceName is an interface.
getPlus has no implementaion.
getMinus has no implementaion.

Abstract Class


Leave a reply                     

Define Abstract Class

Java Abstract Class

Java Example Abstract Class

What is Abstract Class

An abstract class is a class that is declared abstract—it may or may not include abstract methods.
You may subclass an abstract class but cannot instantiate.
A method that is declared without an implementation known as abstract method.
If a class includes abstract methods, the class itself must be declared abstract.
When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, the subclass must also be declared abstract.

Example:

public abstract Class ClassName {
	public abstract int getPlus(int value);
}

public abstract Class SubClassName extends ClassName {
	int decrement = 1;

	public int getMinus(int value) {
		return value - decrement;	
	}
}

public Class SubSubClassName extends SubClassName {
	int increment = 1;

	public int getPlus(int value) {
		return value + increment;	
	}
}

ClassName is an abstract class.
SubClassName is an abstract class.
SubSubClassName has implementaion of method getPlus and is not an abstract class.

Class


Leave a reply                     

Class

Class Example

Define Class

Define Java Class

Java Class Example

What is Class?

What is Java Class?

A class is the blueprint from which individual objects are created.

Example:

Class ClassName {
	int increment = 1;

	public int getCount(int value) {
		return value + increment;	
	}
}

ClassName is user defined name of class.
increment is instance variable.
getCount is instance method.

Java OOPS (Object Oriented Programming System)


Leave a reply                     

Java OOPS Concepts

Java Programming

Java Technology

Object Oriented Programming System

OOPS

OOPS Concepts

Object-oriented programming (OOP) is a programming paradigm that uses “Objects” to develop applications.
Today, C++ and Java are the major OOP languages, while C#, Visual Basic.NET, Python and JavaScript are also popular.
C++, Java, C#, VB.NET, Python are the examples of not pure object oriented languages. Continue reading