I was thinking to write on decorator design pattern in Java when I first wrote 10 interview questions on Singleton Pattern in Java. Since design pattern is quite important while building software and it’s equally important on any Core Java Interview, It’s always good to have clear understanding of various design patterns in Java. In this article we will explore and learn Decorator Design pattern in Java which is a prominent core Java design pattern and you can see lot of its example in JDK itself. JDK use decorator pattern in IO package where it has decorated Reader and Writer Classes for various scenario, for example BufferedReader and BufferedWriter are example of decorator design pattern in Java. From design perspective its also good idea to learn how existing things work inside JDK itself for example How HashMap works in Java or How SubString method work in Java, that will give you some idea of things you need to keep in mind while designing your Class or interface in Java. Now let’s Move on to Decorator pattern in Java.
Tampilkan postingan dengan label java. Tampilkan semua postingan
Tampilkan postingan dengan label java. Tampilkan semua postingan
Core Java coding question converting String to BigDecimal
Label:
bigdecimal,
coding,
converting,
core,
java,
question,
string,
to
And 0
komentar
There are times while coding you need to convert an entity of one data type to another or validate a given input.
Q. Can you write a generic function that converts an amount in String to double amount?
A.
Step 1: Ask the right questions and arrive at a more detailed requirements.
Step 2: Lets use a TDD (Test Driven Development approach).
So, write a skeleton class so that all our unit tests fail.
Next, write the unit tests based on the above requirements so that all fail, but cover the requirements.
Step 3: Implement the functionality, so that all the above unit tests pass.
Now, all green.
Read More..
Q. Can you write a generic function that converts an amount in String to double amount?
A.
Step 1: Ask the right questions and arrive at a more detailed requirements.
- Handling negative amounts like -34.01 or (34.01) with a parenthesis. Parentheses denote a negative value.
- Handling commas in formatted values like 1,205.45, etc.
- Handling negative scenarios like amount being empty as in ( ).
Step 2: Lets use a TDD (Test Driven Development approach).
So, write a skeleton class so that all our unit tests fail.
package com.mycompany.app5;
import java.math.BigDecimal;
import java.text.ParseException;
public class ConvertingAmount
{
public BigDecimal convert(String amount) throws ParseException
{
BigDecimal result = null;
return result;
}
}
Next, write the unit tests based on the above requirements so that all fail, but cover the requirements.
package com.mycompany.app5;
import java.math.BigDecimal;
import java.text.ParseException;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
public class ConvertingAmountTest
{
private ConvertingAmount ca;
@Before
public void setUp()
{
ca = new ConvertingAmount();
}
@Test
public void testPositiveAmount() throws ParseException
{
BigDecimal converted = ca.convert("2255.001");
Assert.assertEquals(new BigDecimal("2255.001"), converted);
}
@Test
public void testNegativeAmount() throws ParseException
{
BigDecimal converted = ca.convert("-2255.001");
Assert.assertEquals(new BigDecimal("-2255.001"), converted);
}
@Test
public void testNegativeAmountWithParanthes() throws ParseException
{
BigDecimal converted = ca.convert("(2255.001)");
Assert.assertEquals(new BigDecimal("-2255.001"), converted);
}
@Test
public void testPosiotiveAmountFormatted() throws ParseException
{
BigDecimal converted = ca.convert("2,255.001");
Assert.assertEquals(new BigDecimal("2255.001"), converted);
}
@Test
public void testNegativeAmountFormatted() throws ParseException
{
BigDecimal converted = ca.convert("-2,255.001");
Assert.assertEquals(new BigDecimal("-2255.001"), converted);
}
@Test
public void testNegativeAmountWithParenthesesFormatted() throws ParseException
{
BigDecimal converted = ca.convert("(2,255.001)");
Assert.assertEquals(new BigDecimal("-2255.001"), converted);
}
@Test(expected = ParseException.class)
public void testExceptionalScenario() throws ParseException
{
String amount = "()";
ca.convert(amount);
}
@Test(expected = ParseException.class)
public void testExceptionalScenario2() throws ParseException
{
String amount = "abc";
ca.convert(amount);
}
}
Step 3: Implement the functionality, so that all the above unit tests pass.
package com.mycompany.app5;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import org.apache.commons.lang.StringUtils;
public class ConvertingAmount
{
public BigDecimal convert(String amount) throws ParseException
{
BigDecimal result = null;
DecimalFormat df = new DecimalFormat("#,#00.00;-#,#00.00"); //positive;negative
//convert (2255.001) to -2255.001 and (2,255.001) to -2255.001
if (StringUtils.isNotBlank(amount) && amount.startsWith("(") && amount.endsWith(")"))
{
String valueStr = amount.substring(1, amount.length() - 1);
Number valInParenthesis = df.parse(valueStr.trim());
result = BigDecimal.valueOf(valInParenthesis.doubleValue()).negate();
amount = result.toPlainString();
}
//parse 2,255.001 and -2,255.001
Number val = df.parse(amount);
result = BigDecimal.valueOf(val.doubleValue());
return result;
}
}
Now, all green.
Difference between List and Set in Java Collection
Label:
and,
between,
collection,
difference,
in,
java,
list,
set
And 0
komentar
What is difference between List and Set in Java is a very popular Java collection interview questions and an important fundamental concept to remember while using Collections class in Java. Both List and Set are two of most important Collection classes Java Program use along with various Map implementation. Basic feature of List and Set are abstracted in List and Set interface in Java and then various implementation of List and Set adds specific feature on top of that e.g. ArrayList in Java is a List implementation backed by Array while LinkedList is another List implementation which works like linked list data-structure. In this Java tutorial we will see some fundamental difference between List and Set collections. Since List and Set are generified with introduction of Generics in Java5 these difference also application to List and Set.
This article is in continuation of my earlier post on Collection e.g. Difference between HashMap vs HashSet, Difference between HashMap and Hashtable and Difference between Concurrent Collection and Synchronized Collection. If you haven't read them already you may find them useful.
Batch processing in Java with Spring batch part 1
Label:
1,
batch,
in,
java,
part,
processing,
spring,
with
And 0
komentar
Make sure that you do this beginner tutorial first Beginner Spring batch tutorial with simple reader and writer | Q. What do you understand by batch processing and why do you need them? A. The idea behind batch processing is to allow a program to run without the need for human intervention, usually scheduled to run periodically at a certain time or every x minutes.The batch process solves
|
Q. What libraries do you need to get started with spring batch
A. The pom.xml file will be the start. Fill in the appropriate versions and the additional dependencies required.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.myapp</groupId>
<artifactId>mybatchapp</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>mybatchapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>org.springframework.batch</groupId>
<artifactId>spring-batch-core</artifactId>
<version>....</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>....</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
<version>...</version>
</dependency>
...other dependencies like hibernate
</dependencies>
...
</project>
Q. What are the key terms of Spring batch?
A.
- JobLauncher: It helps you to launch a job. It uses a JobRepository to obtain a valid JobExecution.
- JobRepository: A persistent store for all the job meta-data information. Stores JobInstances, JobExecutions, and StepExecutions information to a database or a file system. The repository is required because a job could be a rerun of a previously failed job.
- Job: Represents a job. For example, an portfolio processing job that calculates the portfolio value. JobInstance: A running instance of a job. If a job runs every week night, then there will 5 instances of that job in a week.
- JobParameters: Parameters that are used by the JobInstance. For example, the portfolio processing job requires the list of account numbers as the input parameters. The job parameters are passed as command line arguments.
- JobExecution: Every attempt to run a JobInstance results in a JobExecution. If a job fails then it will be rerun and we end up having a single JobInstance with 2 JobExecutions (1 failed execution and 1 successful execution).
- Step: Each job is made up of one or more steps.
- StepExecution: Similar to JobExecution, there are StepExecutions. This represents an attempt to run a Step in a Job.
Q. Can you describe the key steps involved in a typical batch job scenario you had worked on?
A. A simplified batch process scenario is explained below.
The scenario is basically a batch job that runs overnight to go through all the accounts from the accounts table and calculates the available_cash by subtracting debit from the credit.
Step 1: Define a batch control table that keeps metdata about the batch job. The example below shows a batch_control table that process accounts in chunks. The account numbers 000 - 999 ara processed by a job and account_no 1000 - 1999 by another job. This table also holds information about when the job started, when the job finished, status (i.e. COMPLETED or FAILED), last processed account_no, etc.
| job_id | job_name | start_timestamp | end_timestamp | status | account_ no_from | account_ no_to | last_ account_no |
| 1 | accountValueUpdateJob1 | 21/04/2012 3:49:11.053 AM | 21/04/2012 3:57:55.480 AM | COMPLETED | 000 | 999 | 845 |
| 2 | accountValueUpdateJob2 | 21/04/2012 3:49:11.053 AM | 21/04/2012 3:57:55.480 AM | FAILED | 1000 | 1999 | 1200 |
Step 2: To keep it simple, a single data table is used. You need to define a job and its steps. A job can have more than one steps. Each step can have a reader, processor, and a writer. An ItemReader will read data from the accounts table shown below for account numbers between account_from and account_to read from the batch_control table shown above. An ItemProcessor will calculate the availbale_cash and an ItemWriter will update the available_cash on the accounts table.
| account_no | account_name | debit | credit | available_cash |
| 001 | John Smith | 200.00 | 4000.0 | 0.0 |
| 1199 | Peter Smith | 55000.50 | 787.25 | 0.0 |
Step 3: Once the batch job is completed, the batch_contol table will be updated accordingly.
Step 4: Listeners can be used to process errors (e.g. onProcessError(....), onReadError(....), etc) and other pre and post item events like beforeRead(...), afterRead(...), etc. The spring-batch framework make use of the configuration xml file, for example batch-context.xml and the Java classes annotated with @Component to wire up the components and implement the logic.
Step 5: The batch job can be executed via a shell or batch script that invokes the spring-batch framework as shown below. The CommandLineJobRunner is the Spring class that initiates the job by wiring up the relevant components, listeners, daos, etc via the configuration file batch-context.xml. The job parameter that is passed is "accountValueUpdateJob1", which is used to retrieve the relevant job metatdata from the job control table.
my_job_run.sh accountValueUpdateJob1 accountValueUpdateJob1.log
$0 $1 $2
The my_job_run.sh looks something like
...Step 6: The shell script (e.g. my_job_run.sh) or batch file will be invoked by a job scheduler like quartz or
JOB_CLASS=org.springframework.batch.core.launch.support.CommandLineJobRunner
APPCONTEXT=batch-context.xml
SPRING_JOB=availableBalanceJob
CLASSPATH=$JAVA_HOME/bin:.......................
JOB_TO_RUN=$1
...
# the jobParameter is jobName. It is passed via job script argument <jobNameToRun>.
$JAVA_HOME/bin/java -classpath ${CLASSPATH} ${JOB_CLASS} ${APPCONTEXT} ${SPRING_JOB} jobName=${JOB_TO_RUN}"
Unix cron job at a particular time without any human intervention.
This is basically the big picture. The wiring up of spring-batch will be explained in a different post.
- Beginner Spring batch tutorial with simple reader and writer
- Spring batch part -2 - wiring up the components
- Spring batch part 3 -- wiring reader, processor, and writer
- Spring batch advanced tutorial -- writing your own reader
- Spring batch code snippets
Core Java Interview Questions and Answers String concatenation
Label:
and,
answers,
concatenation,
core,
interview,
java,
questions,
string
And 0
komentar
It is a very common beginner level question on String concatenation. Its imperative to understand that NOT all String concatenations are bad. It depends on how you are using it. You need to have the basic understanding that in Java, String is an immutable object and StringBuilder (not thread-safe) and StringBuffer (thread-safe) are mutable. In, Java you can concatenate strings a number of ways with the "+" operator, using the append( ) in StringBuilder and StringBuffer classes, and the other methods like concat( ) in String class.
Q1. Is anything wrong with the following code?
public class StringConcat {
public static String withStringBuilder(int count) {
String s = "Hello" + " " + " peter " + count;
return s;
}
}A1. No, the compiler internally uses a StringBuilder to use two append( ) calls to append the string and converts it to a String object using the toString( ) method.
Note: you can try the javap command described below to see why.
Q2. Is anything wrong with the following code?
public class StringConcat {
public static String withStringBuilder() {
String s = "Hello" + " " + " peter " + " how are you";
return s;
}
}A2. No, the compiler is smart enough to work out that it is a static concatenation and it uses its optimization to concatenate the string during compile-time. If you verify this by using a Java decompiler like jd-gui.exe to decompile the compiled class back, you will get the source code as below.
public class StringConcat
{
public static String withStringBuilder(int count)
{
String s = "Hello peter how are you";
return s;
}
}
You can also use the javap command to dissemble the compiled class file using the following command
C:workspacesprojTestsrc>javap -c StringConcat
Gives the following output
Compiled from "StringConcat.java"The line 0 shows that it has been optimized
public class StringConcat extends java.lang.Object{
public StringConcat();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
public static java.lang.String withStringBuilder(int);
Code:
0: ldc #2; //String Hello peter how are you
2: astore_1
3: aload_1
4: areturn
}
Q3. Is anything wrong with the following code snippet
public class StringConcat {
public static String withoutStringBuilder(int count) {
String str = "";
for (int i = 0; i < count; i++) {
str += i;
}
return str;
}
}A3. Yes. it consumes more memory and can have performance implications. This is because, a String object in Java is immutable. This means, you cant modify a String. If the value of count is 100, then the above code will create 100 new StringBuilder objects, of which 99 of them will be discarded for garbage collection. Creating new objects unnecessarily is not efficient, and the garbage collector needs to clean up those unreferenced 99 objects. StringBuffer and StringBuilder: are mutable and use them when you want to modify the contents. StringBuilder was added in Java 5 and it is identical in all respects to StringBuffer except that it is not synchronized, which makes it slightly faster at the cost of not being thread-safe. The code below creates only two new objects, the StringBuilder and the final String that is returned.
public class StringConcat {
public static String withStringBuilder(int count) {
StringBuilder sb = new StringBuilder(100);
for (int i = 0; i < count; i++) {
sb.append(i);
}
return sb.toString();
}
}Now, if you want to be more pedantic as to how we know that the 100 StringBuilder objects are created, we can use the javap option to our rescue. The javap is a class file dissembler. If you compile the codebase in the question and then run the javap command with the StringConcat.class file as shown below
C:workspacesproj_blueTestsrc>javap -c StringConcat
You will get an output as shown below
Compiled from "StringConcat.java"The dissembled looks cryptic, but if you inspect it carefully the code within the public static java.lang.String withoutStringBuilder(int);
public class StringConcat extends java.lang.Object{
public StringConcat();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
public static java.lang.String withoutStringBuilder(int);
Code:
0: ldc #2; //String
2: astore_1
3: iconst_0
4: istore_2
5: iload_2
6: iload_0
7: if_icmpge 35
10: new #3; //class java/lang/StringBuilder
13: dup
14: invokespecial #4; //Method java/lang/StringBuilder."<init>":()V
17: aload_1
18: invokevirtual #5; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
21: iload_2
22: invokevirtual #6; //Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
25: invokevirtual #7; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;
28: astore_1
29: iinc 2, 1
32: goto 5
35: aload_1
36: areturn
}
Line 5 to 32: is the code within the for loop. The "goto 5" indicates looping back.
Line 10: creates a new StringBuilder object every time
Line 18: uses the StringBuilders append method to concatenate the String.
Line 25: uses the toString( ) method to convert the StringBuilder back to the existing String reference via toString( ) method.
If you run the improved code snippet in the answer through javap, you get the following output
Compiled from "StringConcat.java"As you could see
public class StringConcat extends java.lang.Object{
public StringConcat();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
public static java.lang.String withStringBuilder(int);
Code:
0: new #2; //class java/lang/StringBuilder
3: dup
4: bipush 100
6: invokespecial #3; //Method java/lang/StringBuilder."<init>":(I)V
9: astore_1
10: iconst_0
11: istore_2
12: iload_2
13: iload_0
14: if_icmpge 29
17: aload_1
18: iload_2
19: invokevirtual #4; //Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
22: pop
23: iinc 2, 1
26: goto 12
29: aload_1
30: invokevirtual #5; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;
33: areturn
}
Line 0 to 6: initializes one StringBuilder object outside the for loop.
Line 12 to 26: is the for loop.
Line 19: indicates that since the StringBuilder is mutable, the string is appended via the append method.
Important: The creation of extra strings is not limited to the overloaded mathematical operator "+", but there are several other methods like concat( ), trim( ), substring( ), and replace( ) in the String class that generate new string instances. So use StringBuffer or StringBuilder for computation intensive operations to get better performance. Experiment with javap for the String methods like concat( ), trim( ), substring( ), and replace( ) .
Note: So, javap and jd-gui.exe are handy tools for debugging your application for certain issues. For example, the java decompiler is handy for debugging generics to see how the java source code with generics is converted after compilation by decompiling the .class file back to source code.
How to Convert InputStream to Byte Array in Java 2 Examples
Sometimes we need to convert InputStream to byte array in Java, or you can say reading InputStream as byte array, In order to pass output to a method which accept byte array rather than InputStream. One popular example of this, I have seen is older version of Apache commons codec, while converting byte array to hex string. Though, later version of same library do provide an overloaded method, to accept InputStream. Java File API provides excellent support to read files like image, text as InputStream in Java program, but as I said, sometime you need need String or byte array, instead of InputStream . Earlier we have seen 5 ways to convert InputStream to String in Java , we can use some of the techniques from there while getting byte array from InputStream in Java. If you like to use Apache commons library, which I think you should, there is a utility class called IOUtils, which can be used to easily convert InputStream to byte array in Java. If you don't like using open source library for such kind of thinks, and like to write your own method, you can easily do so by using standard Java File API. In this Java tutorial we will see examples of both ways to convert InputStream to byte array in Java.
10 Example of Hashtable in Java – Java Hashtable Tutorial
These Java hashtable Examples contains some of the frequently used operations on hastable in Java. when I discussed throw of How HashMap or Hashtable works in Java I touched based on inner working of hastable, while in this java hashtable tutorial we will see some examples of hashtable in Java like checking a key exits in hashmap or not or getting all keys and values from HashMap , Iterating on hashtable keys and values using Enumeration etc.
Core Java multi thread coding printing odd and even numbers with two threads
Q. Can you write code to print odd and even numbers by two threads in sequence?
A. Even though this is not a practical question, a handy beginner level question test your ability to write multi-threaded code.
Here are the considerations.
- It needs to be atomic so that the numbers can be printed in sequence. You can use either the AtomicInteger class or maintain two boolean flags like oddPrinted and evenPrinted to coordinate between the two threads.
- Both threads need to have a lock to coordinate odd and even printing. In Java, every object has a lock. So, we can create a Object lock = new Object( ) as the lock for both threads to use.
- The Java Object class has wait and notify/notifyAll methods to facilitate inter thread communication via the Object lock. The notify/notifyAll methods notify the waiting threads to get hold of the lock. Only one thread can execute the code snippet that is synchronized on the lock.
- You need a main method that creates a main thread and then spawn two new threads to print odd and even numbers respectively.
Step 1: The main thread class PrintOddEvenNumbersWithTwoThreads that spawns the two new threads via the thread pool.
package com.mycompany.app6;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
/**
* main thread
*/
public class PrintOddEvenNumbersWithTwoThreads
{
public static void main(String[] args)
{
final int max = 10;
final AtomicInteger i = new AtomicInteger(1); //start with 0
Executor dd = Executors.newFixedThreadPool(2);
final Object lock = new Object();
//the main thread spawns two threads to print odd and even numbers respectively
dd.execute(new OddNumber(max, i, lock));
dd.execute(new EvenNumber(max, i, lock));
do
{
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
while (i.get() != max + 1);
System.out.println("
Done");
System.exit(0);
}
}
Step 2: The OddNumber thread that prints odd numbers.
package com.mycompany.app6;
import java.util.concurrent.atomic.AtomicInteger;
public class OddNumber implements Runnable
{
private int maxNumber;
private AtomicInteger number;
private Object lock;
public OddNumber(int maxNumber, AtomicInteger number, Object lock)
{
this.maxNumber = maxNumber;
this.number = number;
this.lock = lock;
}
public void run()
{
print();
}
public void print()
{
while (number.get() < maxNumber + 1)
{
if (number.get() % 2 == 0)
{
System.out.println(Thread.currentThread().getName() + " --> " + number.getAndAdd(1));
synchronized (lock)
{
lock.notifyAll();//notify all waiting threads on this lock to resume
}
}
else
{
synchronized (lock)
{
try
{
lock.wait(); //wait for the lock
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
}
}
Step 3: The EvenNumber thread that prints even numbers. The implementation is very similar except for the boundary condition that checks for odd or even number.
package com.mycompany.app6;
import java.util.concurrent.atomic.AtomicInteger;
public class EvenNumber implements Runnable
{
private int maxNumber;
private AtomicInteger number;
private Object lock;
public EvenNumber(int maxNumber, AtomicInteger number, Object lock)
{
this.maxNumber = maxNumber;
this.number = number;
this.lock = lock;
}
public void run()
{
print();
}
public void print()
{
while (number.get() < maxNumber + 1)
{
if (number.get() % 2 != 0)
{
System.out.println(Thread.currentThread().getName() + " --> " + number.getAndAdd(1));
synchronized (lock)
{
lock.notify(); //notify all waiting threads on this lock to resume
}
}
else
{
synchronized (lock)
{
try
{
lock.wait(); //wait for the lock
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
}
}
Step 4: Run the main thread class PrintOddEvenNumbersWithTwoThreads to execute the code.
The output:
pool-1-thread-2 --> 1
pool-1-thread-1 --> 2
pool-1-thread-2 --> 3
pool-1-thread-1 --> 4
pool-1-thread-2 --> 5
pool-1-thread-1 --> 6
pool-1-thread-2 --> 7
pool-1-thread-1 --> 8
pool-1-thread-2 --> 9
pool-1-thread-1 --> 10
Done
There are other alternative approaches as described in the NumberGenerator class.
Why use Override annotation in Java Coding Best Practice
Label:
annotation,
best,
coding,
in,
java,
override,
practice,
use,
why
And 0
komentar
@Override annotation was added in JDK 1.5 and it is used to instruct compiler that method annotated with @Override
is an overridden method from super classor interface. Though it may look trivial @Override is particularly useful while
overriding methods which accept Object as parameter just like equals, compareToor compare() method of Comparator
interface. @Override is one of the three built in annotation provided by Java 1.5, other two are @SuppressWarnings and @Deprecated. Out of these three @Override is most used because of its general nature, while @SuppressWarnings is also used while using Generics, @Deprecated is mostly for API and library. If you have read my article common errors while overriding equals method than you have see that one of the mistake Java programmer makes it, write equals method with non object argument type as shown in below example:
5 ways to check if String is empty in Java examples
String in Java is considered empty if its not null and it’s length is zero. By the way before checking length you should verify that String is not null because calling length() method on null String will result in java.lang.NullPointerException. Empty String is represented by String literal “”. Definition of empty String may be extended to those String as well which only contains white space but its an specific requirement and in general String with white space are not considered as empty String in Java. Since String is one of the most frequently used class and commonly used in method arguments, we often needs to check if String is empty or not. Thankfully there are multiple ways to find if String is empty in Java or not. You can also count number of characters in String, as String is represented as character arrayand decide if String is empty or not. If count of characters is zero than its an empty String. In this Java String tutorial we going to see 5 ways to find if any String in Java is empty or not. Here are our five ways to check empty String :
How to get environment variables in Java Example Tutorial
Label:
environment,
example,
get,
how,
in,
java,
to,
tutorial,
variables
And 0
komentar
Environment variables in Java
There are two ways to get environment variable in Java, by using System properties or by using System.getEnv(). System properties provides only limited set of predefined environment variables like java.classpath, for retrieving Java Classpath or java.username to get User Id which is used to run Java program etc but a more robust and platform independent way of getting environment variable in Java program on the other hand System.getEnv() method provide access to all environment variables inside Java program but subject to introduce platform dependency if program relies on a particular environment variable. System.getEnv() is overloaded method in Java API and if invoked without parameter it returns an unmodifiable String map which contains all environment variables and there values available to this Java process while System.getEnv(String name) returns value of environment variable if exists or null. In our earlier posts we have seen How to get current directory in Java and How to run shell command from Java program and in this Java tutorial we will see how to access environment variable in Java.
How to get environment variables in Java - Example
Here is a quick example on How to get environment variable in Java using System.getEnv() and System.getProperty(). Remember System.getEnv() return String map of all environment variables while System.getEnv(String name) only return value of named environment variable like JAVA_HOME will return PATH of your JDK installation directory./**
* Java program to demonstrate How to get value of environment variables in Java.
* Dont confuse between System property and Environment variable and there is separate
* way to get value of System property than environment variable in Java, as shown in this
* example.
*
* @author Javin Paul
*/
public class EnvironmentVariableDemo {
public static void main(String args[]){
//getting username using System.getProperty in Java
String user = System.getProperty("user.name") ;
System.out.println("Username using system property: " + user);
//getting username as environment variable in java, only works in windows
String userWindows = System.getenv("USERNAME");
System.out.println("Username using environment variable in windows : " + userWindows);
//name and value of all environment variable in Java program
Map<String, String> env = System.getenv();
for (String envName : env.keySet()) {
System.out.format("%s=%s%n", envName, env.get(envName));
}
}
}
Output:
Username using system property: harry
Username using environment variable in windows : harry
USERPROFILE=C:Documents and Settingsharry
JAVA_HOME=C:Program FilesJavajdk1.6.0_20
TEMP=C:DOCUME~1harryLOCALS~1Temp
* Java program to demonstrate How to get value of environment variables in Java.
* Dont confuse between System property and Environment variable and there is separate
* way to get value of System property than environment variable in Java, as shown in this
* example.
*
* @author Javin Paul
*/
public class EnvironmentVariableDemo {
public static void main(String args[]){
//getting username using System.getProperty in Java
String user = System.getProperty("user.name") ;
System.out.println("Username using system property: " + user);
//getting username as environment variable in java, only works in windows
String userWindows = System.getenv("USERNAME");
System.out.println("Username using environment variable in windows : " + userWindows);
//name and value of all environment variable in Java program
Map<String, String> env = System.getenv();
for (String envName : env.keySet()) {
System.out.format("%s=%s%n", envName, env.get(envName));
}
}
}
Output:
Username using system property: harry
Username using environment variable in windows : harry
USERPROFILE=C:Documents and Settingsharry
JAVA_HOME=C:Program FilesJavajdk1.6.0_20
TEMP=C:DOCUME~1harryLOCALS~1Temp
Getting environment variable in Java – Things to remember
Java is platform independent language but there are many things which can make a Java program platform dependent e.g. using a native library. Since environment variables also vary from one platform to another e.g. from windows to Unix you need to be bit careful while directly accessing environment variable inside Java program. Here are few points which is worth noting :
1) Use system properties if value of environment variable is available via system property e.g. Username which is available using "user.name" system property. If you access it using environment variable directly you may need to ask for different variable as it may be different in Windows e.g. USERNAME and Unix as USER.
2) Environment variables are case sensitive in Unix while case insensitive in Windows so relying on that can again make your Java program platform dependent.
3) System.getEnv() was deprecated in release JDK 1.3 in support of using System.getProperty() but reinstated again in JDK 1.5.
Thats all on how to get environment variable in Java. Though you have convenient method like System.getEnv() which can return value of environment variable, its better to use System.getProperty() to get that value in a platform independent way, if that environment variable is available as system property in Java.
Other How to tutorials from Javarevisited Blog
Spring Framework Tutorial How to call Stored Procedures from Java using IN and OUT parameter example
Spring Framework provides excellent support to call stored procedures from Java application. In fact there are multiple ways to call stored procedure in Spring Framework, e.g. you can use one of the query() method from JdbcTemplate to call stored procedures, or you can extend abstract class StoredProcedure to call stored procedures from Java. In this Java Spring tutorial, we will see second approach to call stored procedure. It's more object oriented, but same time requires more coding. StoredProcedure class allows you to declare IN and OUT parameters and call stored procedure using its various execute() method, which has protected access and can only be called from sub class. I personally prefer to implement StoredProcedure class as Inner class, if its tied up with one of DAO Object, e.g. in this case it nicely fit inside EmployeeDAO. Then you can provide convenient method to wrap stored procedure calls. In order to demonstrate, how to call stored procedures from spring based application, we will first create a simple stored proc using MySQL database, as shown below.
How to convert decimal to binary octal and hex String in Java Program
This article is about a simple java program which converts decimal number to binary, octal and hexadecimal format. When it was first came into my mind I though I would probably need to write whole code to convert decimal to various other radix or base numbers but when I looked Integer class and saw these two way of converting decimal to binary etc I was simple amazed. It’s indeed extremely easy to do this in java and you can also write this program or use at it is.
Converting decimal to binary in Java Example
Java has many ways to change number system of particular number, you can convert any decimal number into either binary system, hexadecimal system or octal system by following same procedure. here is code example of converting any decimal number into binary number in Java.//first way
//decimal to binary
String binaryString = Integer.toBinaryString(number);
System.out.println("decimal to binary: " + binaryString);
//decimal to octal
String octalString = Integer.toOctalString(number);
System.out.println("decimal to octal: " + octalString);
//decimal to hexadecimal
String hexString = Integer.toHexString(number);
System.out.println("decimal to hexadecimal: " + hexString);
//second way
binaryString = Integer.toString(number,2);
System.out.println("decimal to binary using Integer.toString: " + binaryString);
//decimal to octal
octalString = Integer.toString(number,8);
System.out.println("decimal to octal using Integer.toString: " + octalString);
//decimal to hexadecimal
hexString = Integer.toString(number,16);
System.out.println("decimal to hexadecimal using Integer.toString: " + hexString);
Nice and little tip to convert decimal to binary or decimal to Octal, hex. This comes very handy many times when we want to do a quick conversion.
Related Java Tutorials
Langganan:
Postingan (Atom)

