Java

Java is a set of computer software and specifications developed by Sun Microsystems, which was later acquired by the Oracle Corporation, that provides a system for developing application software and deploying it in a cross-platform computing environment. Java is used in a wide variety of computing platforms from embedded devices and mobile phones to enterprise servers and supercomputers.

Spring Logo

Spring Framework

The Spring Framework provides a comprehensive programming and configuration model for modern Java-based enterprise applications - on any kind of deployment platform. A key element of Spring is infrastructural support at the application level: Spring focuses on the "plumbing" of enterprise applications so that teams can focus on application-level business logic, without unnecessary ties to specific deployment environments.

Hibernate Logo

Hibernate Framework

Hibernate ORM is an object-relational mapping framework for the Java language. It provides a framework for mapping an object-oriented domain model to a relational database.

Showing posts with label Core Java. Show all posts
Showing posts with label Core Java. Show all posts

Friday, September 11, 2015

Write a Java program to get unique characters from String

In this post, we are going to see how to get unique characters from string.
There are several ways to get unique characters from string. In this post, i have implemented two ways.
1. using boolean array.
2. using map.
1. Using Boolean array: In this technique, first we need to convert string into char array. After that we need to iterate all characters. While iterating we need to check that character is already added to array or not. If it is not added then we need to add that character to boolean array and append that character to stringbuilder. If it is already added that character to boolean array, skipping that character to add boolean array.
Code: 
public static String getUniqueCharsUsingBooleanArray(String input) {
        if (input == null || input.length() == 0)
            return input;

        boolean uniqueChars[] = new boolean[256];
        StringBuilder sb = new StringBuilder();
        char chars[] = input.toCharArray();
        for (char ch : chars) {
            if (!uniqueChars[ch]) {
                uniqueChars[ch] = true;
                sb.append(ch);
            }
        }
        return sb.toString();
}
2. Using Map: In this technique, first we need to convert string into char array. After that we need to iterate each character. While iterating we need to check that character is already added or not. If it is not added, adding that character to map and making count is 1. If it is already added then increment that character with count +1. Once all iteration is done then we need to iterate map and append to that character to stringbuilder. Finally convert this stringbuilder to string using toString() method.
Code:
public static String getUniqueCharsUsingMap(String input) {
        if (input == null || input.length() == 0)
            return input;

        Map<Character, Integer> map = new LinkedHashMap<>();
        char chars[] = input.toCharArray();
        for (char ch : chars) {
            if (map.get(ch) == null) {
                map.put(ch, 1);
            } else {
                map.put(ch, map.get(ch) + 1);
            }
        }
        StringBuilder sb = new StringBuilder();
        for (Character uniqueChar : map.keySet()) {
            sb.append(uniqueChar);
        }
        return sb.toString();
}

Program:
package com.ranga;

import java.util.LinkedHashMap;
import java.util.Map;

public class UniqueCharecters {

    public static void main(String[] args) {
        String input = "my name is ranga reddy";
        System.out.println("Unique Characters using way1: " + getUniqueCharsUsingMap(input));
        System.out.println("Unique Characters using way2: " + getUniqueCharsUsingBooleanArray(input));
    }

    public static String getUniqueCharsUsingBooleanArray(String input) {
        if (input == null || input.length() == 0)
            return input;

        boolean uniqueChars[] = new boolean[256];
        StringBuilder sb = new StringBuilder();
        char chars[] = input.toCharArray();
        for (char ch : chars) {
            if (!uniqueChars[ch]) {
                uniqueChars[ch] = true;
                sb.append(ch);
            }
        }
        return sb.toString();
    }

    public static String getUniqueCharsUsingMap(String input) {
        if (input == null || input.length() == 0)
            return input;

        Map<Character, Integer> map = new LinkedHashMap<>();
        char chars[] = input.toCharArray();
        for (char ch : chars) {
            if (map.get(ch) == null) {
                map.put(ch, 1);
            } else {
                map.put(ch, map.get(ch) + 1);
            }
        }
        StringBuilder sb = new StringBuilder();
        for (Character uniqueChar : map.keySet()) {
            sb.append(uniqueChar);
        }
        return sb.toString();
    }
}
Output:
Unique Characters using way1: my naeisrgd
Unique Characters using way2: my naeisrgd
Happy Learning ....!

Sunday, August 23, 2015

Method References in Java8


Method References:
  • Method references refers to methods or constructors without invoking them.
  • We can use lambda expressions to create anonymous methods. 
  • Sometimes, however, a lambda expression does nothing but call an existing method. 
  • In those cases, it's often clearer to refer to the existing method by name.
  • Using Method references refer to the existing method by name, they are compact, easy-to-read lambda expressions for methods that already have a name.
  • In java, method references can be specified by using double colon (::) operator.
  • Method reference can be expressed using the lambda expression syntax (->) in order to make it simple :: operator can be used.
Syntax:
           <class_name or instance_name>::<method_name>
Example:
/**
 * @author Ranga Reddy
 * @version 1.0
 */
public class MethodReferenceExample {
    public static void main(String[] args) {
        
        // with out using method reference
        new Thread(
                () -> {System.out.println("Hello, Mr. Ranga"); }
        ) {
            
        }.run();;
        
        // with using method reference
        new Thread(MethodReferenceExample:: sayHello) {
            
        }.run();
        
    }
    
    public static void sayHello() {
        System.out.println("Hello, Mr. Ranga");
    }
}
Types of Method References:
There are four types of method references:

Method Reference Type
Syntax
Example
Reference to a static method
ClassName::staticMethodName
String::valueOf
Reference to a bound non-static method
ObjectName::instanceMethodName
s::toString
Reference to an instance method of an arbitrary object of a particular type
ClassName::instanceMethodName
Object::toString
Reference to a constructor
ClassName::new
String::new
Reference to a static method:
We can call static method references by using ContainingClass::staticMethodName
Example:
public class MethodReferenceExample {
    public static void main(String[] args) {        
        // Reference to a Static Method     
        new Thread(MethodReferenceExample::sayHello).start();
    }       
    public static void sayHello() {     
        System.out.println("Hello, Mr. Ranga");
    }
}
Reference to a bound non-static method:
We can call non-static method using ObjectName:: instanceMethodName
Example:

public class MethodReferenceExample {
    public static void main(String[] args) {
        // Reference to an Instance Method of a Particular Object
        String name = "My name is Ranga Reddy";
        printName(name::toString);      
    }
    
    private static void printName(Supplier<String> supplier) {
        System.out.println(supplier.get());
    }
}
Reference to an instance method of an arbitrary object of a particular type:
We can call non-static method using ClassName:: instanceMethodName

Example:
public class MethodReferenceExample {
    public static void main(String[] args) {
        // Reference to an Instance Method of an Arbitrary Object of a Particular Type
        String[] names = { "Ranga", "Reddy", "Vinod", "Raja", "Manu", "Teja", "Vasu" };     
        Arrays.sort(names, String::compareToIgnoreCase);
        System.out.println(Arrays.toString(names));     
    }
}
Reference to a bound non-static method:
We can call non-static method using ClassName:: new
Example:
@FunctionalInterface
interface EmployeeFactory {
    Employee getEmployee(long id, String name, Integer age);
}

class Employee {
    private long id;
    private String name;
    private int age;
        
    public Employee() {     
        this(1, "Ranga", 27);
    }
    
    public Employee(long id, String name, int age) {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Employee [id=" + id + ", name=" + name + ", age=" + age + "]";
    }   
}

public class MethodReferenceExample {
    public static void main(String[] args) {                
        // Reference to constructor
        EmployeeFactory employeeFactory = Employee :: new;
        Employee employee = employeeFactory.getEmployee(1, "Ranga Reddy",27);
        System.out.println(employee);       
    }
}
When to use method references:
When a lambda expression is invoking already defined method, then we can replace it with reference to that method.
When we can't use method references:
We can't pass arguments to the method references. So that places we can't use method references.
References:
  1. https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html
  2. http://java8.in/java-8-method-references/
  3. http://www.informit.com/articles/article.aspx?p=2191424

Write a Java Program to convert String value into Integer value with out using parseInt() method.


In this post, we are going to learn how to convert string value into integer value with out using the parseInt() method.

package com.ranga;

/**
*
* This class is used to convert the String value into Integer.
* @author Ranga Reddy
* @version 1.0
*
*/

public class StringToInteger {

public static void main(String[] args) {
String string = "123456";
System.out.println("String value: "+ string);
int integerValue = convertStringToInteger(string);
System.out.println("Integer value: "+ integerValue);
}

/**
* Used to convert the String to Integer.
* @param str - the value of a string value
* @return the integer value.
*/

public static int convertStringToInteger( String str ) {
if(str == null)
throw new NullPointerException("Value is "+str);

int i = 0, intValue = 0;
boolean isNegativeValue = false;
int strLength = str.length();
// checking the first character is negative or not. if it is negative then i start with 1.
if( str.charAt(0) == '-' ){
isNegativeValue = true;
i = 1;
}

for(;i<strLength; i++) {
int value = str.charAt(i) - '0';
if( value > -1 && value < 10 ) {
intValue *= 10;
intValue += value;
} else {
throw new NumberFormatException("Invalid integer string. Value is "+str);
}
}

// if value is negative then adding the prefix is -
if( isNegativeValue ) {
intValue = -intValue;
}
return intValue;
}
}

Input 1: 
String string = null;
Output 1:
Exception in thread "main" java.lang.NumberFormatException: null value can't be convert into integer.
Explanation: If the string value is null then throwing the NumberFormatException.

Input 2:
String  string = "143";
Output 1:
143
Explanation: 
Initial values of 
int i = 0;
int intValue = 0;
boolean isNegativeValue = false;
int strLength = str.length() = 3;

Then checking the string 0th position value will be -ve or not because number can be positive or negative.
if(str.charAt(0) == '-') {

}

If it is true then number start position will be 1 on words. so now i value will be. And also make isNegativeValue value will be true. In the above case 0th position is not negative value. so i value start with 0 only.
then get the each position value and multiply with 10 and add into the end of integer value.

i =0
value = str.charAt(i) - '0' = str.charAt(0) - '0' = 49 - 48 = 1
intValue = 0 * 10 = 10
intValue = intValue +  value = 0 + 1 = 1

Note: str.charAt(1) returns the ASCII value of 1. ASCII value of 1 is 49 and then substracting the ASCII value of 0 is 48

i = 1
value = str.charAt(1) = 52 - 48 = 4
intValue = 1 * 10 = 10
intValue = 10 + 4 = 14

i = 2
value = str.charAt(2) = 51 - 48 = 3
intValue = 14 * 10 = 140
intValue = 140 + 3 = 143

Note: value should be always between 0 to 9 only. If it not then throwing the NumberFormatException








Monday, August 17, 2015

Java8 New Features

New Features of Java 8:

The following are the major features of Java 8:

Wednesday, July 15, 2015

Core Java

Core Java Posts Coming Soon...

Saturday, October 27, 2012

Spring MVC Hello World Example

In this post, we are going to see how to implement Spring MVC HelloWorld example.
Step 1:
The initial step is to create Dynamic Web Project in eclipse. To create a new Dynamic project in Eclipse IDE select File -> Dynamic Web Project.
Step 2:
After that New Dynamic Project Window will appear on the screen and you will enter the web application name in the Project name text box. Enter SpringHelloWorld in the Project Name and then click Next button.

Step 3:
Add Spring Web MVC jar files.
spring-webmvc.jar
spring.jar
commons-logging.jar
Step 4:
Now we will created a index.jsp in project's WebContent  folder. In the jsp file we will create a new hyperlink "Click Here" that will be linked to hello.do page.  The code of index.jsp is:
index.jsp

<html>
<head>
<title>Spring Demo</title>
</head>
<body>
<a href="hello.do">Click Here</a>
</body>
</html>
Step 5:
Now we will configure the DispatcherServlet in web.xml file. The DispatcherServlet will be configured to process all the request ending with *.do
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>SpringHelloWorld</display-name>
<description>Hello world Application</description>
<servlet>
<servlet-name>controller</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>controller</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
Step 6:
Now we will create a new xml file called controller-servlet.xml in the WEB-INF folder of the web application. This is the main configuration file for the Spring MVC.
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
Then we will define the url mapping with the Controller bean as shown below:

<property name="mappings">
<props>
<prop key="/hello.do">helloController</prop>
</props>
</property>
Finally we will define the Controller bean as shown below:
<bean id="helloController" class="com.ranga.HelloWorld"> </bean>
controller-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"
>
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/hello.do">helloController</prop>
</props>
</property>
</bean>
<bean id="helloController" class="com.ranga.HelloWorld" />
</beans>
Step 7:
After that we will creates the controller class in the project src folder. This will be used as the controller for the hello.jsp request. The code of the  HelloWorld.java calss is:

HelloWorld.java

package com.ranga;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

public class HelloWorld implements Controller {
@Override
public ModelAndView handleRequest(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception {
System.out.println("HelloWorld");
String str = "Hello World!";
return new ModelAndView("hello.jsp", "message", str);
}
}
Step 8:
After that we will create a hello.jsp in the WEB-INF folder. The WEB-INF/hello.jsp code is:
hello.jsp

<%@page isELIgnored="false" %>
${message}
Step 9:
To run the example select Run -> Run As -> Run On Server from the menu and then run the application on tomcat server. Eclipse will start Tomcat server and deploy the application on the Tomcat. Ellipse will also open the application in it internal browser as shown below:
Click on the "Click Here" link to test the application. It should display the "Hello World!" message as shown below.

Friday, September 14, 2012

Spliting a String without using any built in functions in Java

In this post, we are going to see how to split a string without using any built in functions.
package com.ranga;

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

/**
* Write a Java program to split a string with out using any bulit methods like
* split(), StringTokenizer class methods.
*
* @author Ranga Reddy
* @version 1.0
*/

public class SplitString {
public static void main(String[] args) {
String str = "Welcome to JavabyRangaReddy blog";
String delimiter = " "; // here delimiter is space
List<String> list = new ArrayList<String>(); // list is used to store the words
int i, start = 0, end = 0;
for (i = str.indexOf(delimiter); i != -1; i = str.indexOf(delimiter, i + 1)) {
end = i;
list.add(str.substring(start, end)); // by using substring we can get the one word
start = i;
}
list.add(str.substring(end)); // this is used to add the last word
System.out.println(list); // print the list

// Converting list to array of strings
String words[] = (String[]) list.toArray(new String[list.size()]);
for (String word : words) {
System.out.println(word.trim());
}
}
}
Output:
[Welcome,  to,  JavabyRangaReddy,  blog]
Welcome
to
JavabyRangaReddy
blog

Saturday, November 19, 2011

Top 8 Java People you should know


Top 8 Java People You Should Know
Here are the top 8 Java people, they’re created frameworks, products, tools or books that contributed to the Java community, and changed the way of coding Java.
1. Father of the Java programming language

James Gosling, generally credited as the inventor of the Java programming language in 1994. He created the original design of Java and implemented its original compiler and virtual machine. For this achievement he was elected to the United States National Academy of Engineering. On April 2, 2010, he left Sun Microsystems which had recently been acquired by the Oracle Corporation. Regarding why he left, Gosling wrote on his blog that “Just about anything I could say that would be accurate and honest would do more harm than good.”
Related Links
  1. James Gosling Blog
  2. James Gosling Wiki
2. Java Collections Framework

Joshua Bloch, led the design and implementation of numerous Java platform features, including JDK 5.0 language enhancements and the award-winning Java Collections Framework. In June 2004 he left Sun and became Chief Java Architect at Google. Furthermore, he won the prestigious Jolt Award from Software Development Magazine for his book, “Effective Java”, which is arguably a must read Java’s book.
Related Links
  1. Joshua Bloch Twitter
  2. Joshua Bloch Wiki
News & Interviews
  1. Effective Java: An Interview with Joshua Bloch
  2. Rock Star Josh Bloch
Joshua Bloch Books
  1. Effective Java (2nd Edition)
  2. Java Concurrency in Practice
3. JBoss Founder

Marc Fleury, who founded JBoss in 2001, an open-source Java application server, arguably the de facto standard for deploying Java-based Web applications. Later he sold the JBoss to RedHat, and joined RedHat to continue support on the JBoss development. On 9 February 2007, he decided to leave Red Hat to pursue other personal interests, such as teaching, research in biology, music and his family.
Related Links
  1. Marc Fleury Wiki
  2. Marc Fleury Blog
  3. JBoss Application Server
News & Interviews
  1. Could Red Hat lose JBoss founder?
  2. JBoss founder Marc Fleury leaves Red Hat, now what?
  3. JBoss’s Marc Fleury on SOA, ESB and OSS
  4. Resurrecting Marc Fleury
4. Tomcat & Ant Founder
James Duncan Davidson, while he was software engineer at Sun Microsystems (1997–2001), created Tomcat Java-based web server, still widely use in most of the Java web projects, and also Ant build tool, which uses XML to describe the build process and its dependencies, which is still the de facto standard for building Java-based Web applications.
Related Links
  1. James Duncan Davidson Twitter
  2. James Duncan Davidson Wiki
  3. James Duncan Davidson personal blog
  4. Apache Ant
  5. Apache Tomcat
5. Test Driven Development & JUnit Founder

Kent Beck, creator of the Extreme Programming and Test Driven Development software development methodologies. Furthermore, he and Erich Gamma created JUnit, a simple testing framework, which turn into the de facto standard for testing Java-based Web applications. The combine of JUnit and Test Driven Development makes a big changed on the way of coding Java, which causes many Java developers are not willing to follow it.
Related Links
  1. Kent Beck Twitter
  2. Kent Beck Wiki
  3. Kent Beck Blog
  4. JUnit Testing Framework
  5. Extreme Programming Wiki
  6. Test Driven Development Wiki
News & Interviews
  1. Kent Beck: “We thought we were just programming on an airplane”
  2. Interview with Kent Beck and Martin Fowler
  3. eXtreme Programming An interview with Kent Beck
Kent Beck Books
  1. Extreme Programming Explained: Embrace Change (2nd Edition)
  2. Refactoring: Improving the Design of Existing Code
  3. JUnit Pocket Guide
6. Hibernate Founder

Gavin King, is the founder of the Hibernate project, a popular object/relational persistence solution for Java, and the creator of Seam, an application framework for Java EE 5. Furthermore, he contributed heavily to the design of EJB 3.0 and JPA.
Related Links
  1. Gavin King Blog
  2. Hibernate Wiki
  3. Hibernate Framework
  4. JBoss seam
News & Interviews
  1. Tech Chat: Gavin King on Contexts and Dependency Injection, Weld, Java EE 6
  2. JPT : The Interview: Gavin King, Hibernate
  3. JavaFree : Interview with Gavin King, founder of Hibernate
  4. Seam in Depth with Gavin King
Gavin King Books
  1. Java Persistence with Hibernate
  2. Hibernate in Action (In Action series)
7. Spring Founder

Rod Johnson, is the founder of the Spring Framework, an open source application framework for Java, Creator of Spring, CEO at SpringSource. Furthermore, Rod’s best-selling Expert One-on-One J2EE Design and Development (2002) was one of the most influential books ever published on J2EE.
Related Links
  1. Rod Johnson Twitter
  2. Rod Johnson Blog
  3. SpringSource
  4. Spring Framework Wiki
News & Interviews
  1. VMware.com : VMware to acquire SpringSource
  2. Rod Johnson : VMware to acquire SpringSource
  3. Interview with Rod Johnson – CEO – Interface21
  4. Q&A with Rod Johnson over Spring’s maintenance policy changes
  5. Expert One-on-One J2EE Design and Development: Interview with Rod Johnson
Rod Johnson Books
  1. Expert One-on-One J2EE Design and Development (Programmer to Programmer)
  2. Expert One-on-One J2EE Development without EJB
8. Struts Founder

Craig Mcclanahan, creator of Struts, a popular open source MVC framework for building Java-based web applications, which is arguably that every Java developer know how to code Struts. With the huge success of Struts in early day, it’s widely implemented in every single of the old Java web application project.
Related Links
  1. Craig Mcclanahan Wiki
  2. Craig Mcclanahan Blog
  3. Apache Struts
News & Interviews
  1. Interview with Craig McClanahan
  2. Struts Or JSF?