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

Friday, 19 February 2016

Arithmetic Operators in Java - Live practical examples : Part 1

In today's post we'll cover the topic of arithmetic operators in Java with some real live examples. In this post, we'll skip the theory and go straightaway for some practical examples. With these examples, you will get to grasp and understand the operator functions much quicker than ever.

Check out the following code in which we have used multiple combinations of arithmetic operators in different positions.

package com.ironcladzone;

public class operator1 {

public static void main(String[] args) {
System.out.println("Example 1 :" + 3 + 4 + 5);
System.out.println("Example 2 : " + 3 + 4 * 5);
System.out.println("Example 3 : " + 3 + 12 * 10);
System.out.println("Example 4 : " + 3 * 4 + 5);
System.out.println("Example 5 : " + 3 * 4 / 5);
System.out.println("Example 6 : " + 5 / 4 * 5);
System.out.println("Example 7 : " + 10 / 4 + 5);
System.out.println("Example 8 : " + 10 + 4 / 5);
System.out.println("Example 9 : " + 10 + 15 / 5);
System.out.println("Example 10 : " + 125 / 10 / 5);
System.out.println("Example 11 : " + 50 / 10 / 5);
System.out.println("Example 12 : " + 23 / 10 / 5);
System.out.println("Example 13 : " + 23 / 10 / 5 + 4);
System.out.println("Example 14 : " + 3 + 4 + 5 / 7);
System.out.println("Example 15 : " + 3 + 4 + 5 * 2);
System.out.println("Example 16 : " + 3 + 5 / 5 * 2);
System.out.println("Example 17 : " + 3 + 22 / 5 * 2);
System.out.println("Example 18 : " + 3 + 7 / 5 * 2);
System.out.println("Example 19 : " + 2 + 8 / 5 * 2);
System.out.println("Example 20 : " + 3 * 9 / 5 + 2.59);

}


}

Output : 

Example 1 :345
Example 2 : 320
Example 3 : 3120
Example 4 : 125
Example 5 : 2
Example 6 : 5
Example 7 : 25
Example 8 : 100
Example 9 : 103
Example 10 : 2
Example 11 : 1
Example 12 : 0
Example 13 : 04
Example 14 : 340
Example 15 : 3410
Example 16 : 32
Example 17 : 38
Example 18 : 32
Example 19 : 22
Example 20 : 52.59

If you observe closely, you may find a few of the combinations are tricky. For instance, note that the + sign we have used, is for string concatenation and not to be confused with the plus sign used for addition.

This was just the first set of live examples. Another exhaustive post on more examples is on its way. Stay tuned folks. Am also quite sure this code will help you cover the basic operator concepts if you're planning to give the Oracle Java Certification 1Z0-803. Good luck guys. Signing out.

Sunday, 14 February 2016

Print File size using Java

If you ever want to print the file size using Java, use the following piece of code below :

import java.io.*;

public class FileSize {

public static void main(String[] args) {
File f = new File("//Users//ironcladzone//Downloads//image1.jpg");
System.out.println("File size in bytes = " +f.length());
System.out.println("\nFile size in kb = " +f.length()/1024);

}


}

Output :

File size in bytes = 241833

File size in kb = 236

Note that when we use the length() function, it gives us the file size in bytes. For getting output in kilobytes, divide it by 1024. If you want size in megabytes, again divide it by another 1024. So on and so forth...

Saturday, 13 February 2016

Create a new directory using Java

In today's example we'll create a new directory using Java. Check out the following code below :

import java.io.*;

public class Create_Directory {

public static void main(String[] args) {
File dir = new File("//Users//ironcladzone//Downloads//TestDir");
boolean DirectoryCreated = dir.mkdir();
if (DirectoryCreated)
System.out.println("Created a new directory");
else
System.out.println("Directory not created");
}


}

Note that we have used the function mkdir() as expected. It returns the value "true" if the directory is created or "false" if not created. We use the variable 'DirectoryCreated' to store this boolean value, based on which it prints a message.

Try executing this program twice. The first time when you execute the program, a directory gets created and you get the output like :

Created a new directory

The second time when you execute the code, a directory does not get created since it already exists. So you'll get the output like :

Directory not created

Accept User Input in Java

For accepting user input in Java refer the following piece of code below :

import java.io.*;

public class User_Input {

public static void main(String[] args) {
String inp="";
System.out.println("Please enter your name : ");
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
inp=br.readLine();
}
catch(IOException e) {
e.printStackTrace();
}
System.out.println("Welcome " +inp);

}


}

Output:
Please enter your name : 
IronCladWriter
Welcome IronCladWriter

Make sure to import java.io.* so as to use the input/output functions. Notice that we have wrapped an InputStreamReader within a BufferedReader. Guys, do check out detailed documentation on BufferedReader and InputStreamReader for better understanding.

Friday, 12 February 2016

Basic string manipulation in Java with Real Examples : Part 1

Hi guys, how you doing today? I just noticed I haven't written anything about Java in quite some time now. Well let's bring Java back into the spotlight with this light subject on basic string manipulation.

Lets try to cover some simple examples covering different scenarios :

Illustration 1 : Extract a substring from a string

In this example we simply extract a part of the string.

public class String_manip {

public static void main(String[] args) {
 String str = "Hello guys. Welcome to IroncladZone";
 
 String sub_str = str.substring(23, 35);
 
 System.out.println (sub_str);
}

}

Output : IroncladZone

Illustration 2 : Replace a substring from a string

In this example we replace the word "guys" with "goodfellas" within the string.

public class String_manip {

public static void main(String[] args) {
String str = "Hello guys. Welcome to IroncladZone";
String replaced_str = str.replace("guys", "goodfellas");
System.out.println(replaced_str);

}

}

Output : Hello goodfellas. Welcome to IroncladZone

Note that strings are immutable. Their value cannot be changed once its created. However we can create a new string with the replaced word/part.

Illustration 3 : Join / Combine two strings i.e Concatenation

In this we simply join 3 strings together using +

public class String_manip {

public static void main(String[] args) {
String str1 = "Welcome";
String str2 = "to";
String str3 = "IroncladZone";
System.out.println(str1 + str2 + str3);
System.out.println(str1 + " " + str2 + " " + str3);

}

}

Output : 
WelcometoIroncladZone
Welcome to IroncladZone

Illustration 4 : Print the length of the string


public class String_manip {

public static void main(String[] args) {
String str = "Welcome to IroncladZone";
System.out.println(str.length());

}

}

Output :
23

Note the length() function used to show the length of the string.

Illustration 5 : Split a string on a whitespace

public class String_manip {

public static void main(String[] args) {
String str = "Welcome to IroncladZone";
String[] new_str = str.split("\\s+");
System.out.println(new_str[0]);

}


}

Output :
Welcome

Notice the \\s+ regex for the whitespace.

That's it for today fellas. I'll try to include some more advanced scenarios in a 2nd part of this post. There's more to come guys, stay tuned...

Thursday, 11 February 2016

Create Runnable Jar in Eclipse

Here's a quick pictorial on how to create an executable jar in Eclipse. Assuming you have a Java project in place, let's take a quick look into the steps.

Go to File menu -> Export. Expand Java to choose Runnable JAR File and click Next. Check out the screenshot for reference.


In the next screen, you simply have to choose the Destination folder where you want to save the executable Jar. Also choose the java application's Launch configuration. It also lets you save an Ant script describing the Jar file that you created. Check out this link for official detailed reference.

Monday, 8 February 2016

How to Set JAVA_HOME environment variable in Mac OS X

Check out a quick reference guide to set the JAVA_HOME environment variable in Mac OS X.

Open terminal and type the following :

  • sudo vim ~/.bash_profile
  • Enter your password
  • Now in the vim editor, insert the following text :
export JAVA_HOME=(/usr/libexec/java_home)
  • Save the .bash_profile from the vim editor using :wq
  • Now type the following in terminal :
source ~/.bash_profile

Confirm your changes by typing the following in terminal :

echo $JAVA_HOME

You should see the value/path of JAVA_HOME environment variable you just set as above.



Sunday, 20 April 2014

MySQL JDBC Connector on Mac OSX

If you're working on any Java based program which uses MySQL as it's back-end database, you might find this article extremely helpful.

In order to pull data from the MySQL database, it is first important to establish a connection with it so that the script can talk with it.

The connection can be established by using the MySQL JDBC driver. Now, this driver needs to be separately downloaded. Here's the download link btw. If you're working on Mac OSX, please select the platform-independent version of the Connector from the drop down.

Once downloaded, untar the tar (or unzip the zip file). Copy the mysql-connector-x.x-bin.jar to /Library/Java/Extensions.

If you're using Eclipse IDE for editing class files, you need to make some changes in Eclipse's preferences. So go to Eclipse -> Preferences -> Java -> User Libraries. Click 'New' to create a new user library named as "MYSQL_CONNECTOR_LIBRARY" for instance. Now, click "Add External JARs..." button and browse to the downloaded jar : mysql-connector-x.x-bin.jar.

So if you're Java application is trying to connect to MySQL database, the following code snippet might come in handy for quick reference.

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


try {

connection=DriverManager.getConnection("jdbc:mysql://localhost:3306", "username", "password");

}

Tuesday, 8 April 2014

Check if a file exists using Java

I have long thought about including some content about Core Java concepts on my blog. So here is one of the first ones in the series, which covers some basic Java fundamentals. I assume you have some knowledge about using the Eclipse IDE for project creation. I also assume that you have some basic idea about the Java language (theoretical concepts like OOPS, Inheritance, Data abstraction etc). Don't worry if you don't know much because I plan to cover a few posts on those basics later.

At this point, this post here is all about writing a simple script in Java for checking if a specific file exists at a certain location. You may use the following example for quick reference.

Briefly speaking, we would be importing the java.io.File class and use one of it's methods - isFile.

Please note that the best preferred function to check if a files exists is exists(). In this example, we see how isFile() can also be used to check the same.

Here we go - Create a new class file in Eclipse named as "CheckFileExists_Example". If you maybe aware, the class name and filename has to be the same in Java.

package my.ironcladzone.com;

import java.io.IOException;
import java.io.File;

public class CheckFileExists_Example {

    public static void main(String[] args) {
            
            File f = new File("/usr/tmp/DocuTest.txt");
           
            if (f.isFile()) {
               
                System.out.println("File exists \n");
               
            } else {
       
                System.out.println("File does not exist \n");
            }
     }

}

Here, the method isFile is used to check if "DocuTest.txt" is a file or not. It returns a boolean value - true or false, depending on whethere it actually is a file or not. It will return false if the absolute path mentioned by us, turns out to be a directory.

Play around with code and check for yourself. Edit the path as just :

File f = new File("/usr/tmp/");

Now, the isFile function returns false since the path mentions the '/usr/tmp' location, which is a directory and not a file. So it will directly jump to the else block and print our "File does not exist" statement.

Try one more scenario - specify an imaginary filename in the path. Let's say for example xyz123.txt.

File f = new File("/usr/tmp/xyz123.txt");

It will return false if a filename xyz123.txt does not exist at a specific location.

The point here is how isFile() function can also be used, instead of traditional exists() function for checking if a specific filename exists. It serves a same-to-similar purpose.

I'd cover some more basic topics on I/O in Java i.e reading from files, writing to files in some future posts. So, stay tuned folks. In the meantime, do post your comments for any suggestions & tips. Ciao.

Wednesday, 5 March 2014

Artifactory on Mac OS X

Recently, while trying to install Artifactory on my Mac OS X machine, I encountered a weird error. Finding a solution was a bit tricky and took some time to figure it out.

Artifactory is basically an open source repository manager. I downloaded the latest current version v3.1.1.1. In this tutorial, we'll cover the easy method using hot deployment on servlet container.

Note that Artifactory comes pre-bundled with it's war file which we can deploy onto Tomcat. Although it does come pre-loaded with it's own container, I wanted to deploy the war using Tomcat 7. Since I already have Tomcat 7 installed on my machine.

When I logged on to Tomcat manager and tried to deploy the Artifactory war, I got the generic looking error : FAIL - application at context path could not be started.

So I fired up the terminal and looked into the Tomcat Catalina logs and here's what I came across :




The error "Setting property 'disableURLRewriting' to 'true' did not find a matching property." was looking really strange. So I googled a bit and realised that Artifactory needs JDK 1.7 to run. Refer this forum for some insights.

Now since Mac machines come pre-loaded with Apple supplied Java 6, I was in a kind of a fix. I wondered what to do. Should I download and install Java 7 & uninstall Java 6?

However I was skeptical of uninstalling Java 6. Also, I was not quite sure about what overall impact it would have by uninstalling Java 6 altogether. Since I mentioned previously that Google Chrome does not work with 64-bit Java 7. I spent some time doing impact analysis but didn't quite reach a conclusive decision. A little bit of coffee did the trick :)

Now, here's the workaround. Download the JDK 1.7 for Mac from this link. Now luckily I had the Eclipse IDE with Tomcat plugin ready. If you don't have this setup yet, I highly recommend working with the Eclipse IDE. Lots of customizations are possible.

Open Tomcat Preferences and and expand Java > Installed JRE from the left menu. Click Add. Now browse to /Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home. Describe it with some name like Jdk 1.7. Apply settings and don't exit the preferences as yet.

Make sure you only mention the path till Home. If you mention path further like .../Contents/Home/bin/java, you will see an error like "Target is not a JDK root. Java executable not found."

Check the screenshot for reference.




Now, scroll down the preferences' left pane and expand Tomcat > JVM Settings. From the drop down, select Jdk 1.7 that just defined above. So henceforth, Tomcat container will only be invoked using Jdk 1.7. If for any reasons, you have to invoke using Java 6, you can always choose Apple supplied Java 6 from this list. Check the screenshot for reference.




Now simply hit the Start Tomcat button. Bingo. Wait and watch the console till you see that Artifactory has started. Something like this : 

###########################################################
### Artifactory successfully started (29.031 seconds)   ###
###########################################################

Now, all you have to do is open browser to localhost:<listener-port-no>/artifactory. By default, tomcat's listener port is 8080. You can modify it if you want to.




In my next tutorial, I'll post about working with Artifactory & Maven repositories. Stay tuned folks.

Friday, 28 February 2014

Info on Google Chrome with Java 7 on Mac OS X

Fact Check : Guys, did you know the following fact about Chrome : Google Chrome does not work with Java 7 on Mac OS X. Turns out that the 32-bit Chrome browser does not support Oracle Java 7 on Mac OS X.



Folks, please make a note of this, in case you're planning to upgrade Apple supplied Java 6 to Java 7.

Also note that Chrome works perfectly fine with Java 6 while other browsers like Mozilla Firefox & Apple Safari do support Java 7 out of the process.

Refer the following official Oracle Java link about this fact.

Chrome's 64-bit version is among it's future plans as listed on this Chromium Design Documents page.

Friday, 27 December 2013

Move Task - Ant

Move task in Ant is used to move a file or a directory or a set of files to a new directory.


  • Move task can also be used rename a single file (analogous to mv command in unix)
Eg:

<move file="test.txt" tofile="test_updated.txt" />


  • You can use to move a file to a specific directory as follows:
Eg:

<move file="test.txt" todir="/usr/var/move_here/" />


  • Move a set of files to a certain directory

Eg:

<move todir="/usr/var/mover_here/">
    <fileset dir="/my/src/dir_to_be_moved">
         <include name = **/*.jar >
         <exclude name = **/ant.jar">
     </fileset>
</move>  

A detailed official guide of the Move task and its parameters can be found here.



Rename build properties in Ant

It is possible to rename the build.properties file to something more specific to your environment. For instance, you can have separate build.properties file for DEV, QA, UAT or Production environment, if you want to.

You could rename it to lets say build-dev.properties or build-test.properties

Accordingly, rename the property tag in build.xml where you define the properties file.

Eg:

<property file="${user.home}/build-test.properties"/>

Thursday, 26 December 2013

Increase memory used by JVM for Ant builds

Sometimes for builds using Apache Ant, we come across the Out of Memory error. In order to increase the memory used by JVM for the build, do the following:

Set ANT_OPTS=-Xms256m -Xmx1024m -XX:MaxPermSize=120m

Sunday, 22 December 2013

Ant - read from build.properties

While performing builds using Ant, you must be aware about the build.xml file. The build.xml can read the parameter values from the build.properties file, which usually is one level up.

You have to define a property which mentions the properties file from which the script would read the values.

<property file = "build.properties" />
Related Posts Plugin for WordPress, Blogger...
eXTReMe Tracker