Archive for December, 2009

Ways of Creating Strings in java: String Literal Pool

    String Literal Pool:

String str=”hello”;
willl go to String literal pool managed by String class and will reuse the “hello” string if it is already present, otherwise creates new “hello” in pool.
String str=new String(“hello”)
every time creates new object in heap.

Garbage collector never looks in String literal pool. String literal pool is also a part of heap memory.

So:

String s1 = “hello”;
String s2 = “hello”;
System.out.println(s1==s2);
// true.

Object s2 is the same object with s1. But if you create using new operator:

String s1 = “hello”;
String s2 = new String(“hello”);
System.out.println(s1==s2);
//false
Here is a great article about Strings.

Leave a comment

Using Scanner class to get input from user in java

java.util.Scanner class provides a way to get input from user:

Scanner scanner = new Scanner(System.in);

If input is String:

String string= scanner.nextLine();//to read input as a whole line

or

String string= scanner.next(); // to read single word

To read integers:

int i= scanner.nextInt();

Here is an article helpful on Scanner.

,

Leave a comment

Narrowing: Typecasting to Subclass

    Case 1: (ALLOWED):

Super super = new Sub();
Sub sub = (Sub) super;

It is called Narrowing.

Use:
We have an object of subclass which is referenced by Superclass reference. We don’t have any other reference to that object. Now we want to get subclass reference to that object to get access to subclass methods. Then we can perform narrowing. Here object remains the same(of subclass), what narrowing does is gives a reference of subclass to that object.

Case 2: (Gives ClassCastException at run time):


Super super = new Super();
Sub sub = (Sub) super;

Reason:
If object itself is of superclass, we can not have a reference of subclass to it. The superclass object does not have subclass specific members in its scope. So if it is typecasted to subclass, it will still have the superclass members in its scope, so there is no use of narrowing it to subclass. So it is not allowed.
Why the error is at run time, not compile time: At compile time, the compiler does not know what object the super class reference is pointing to. Compiler knows about the reference variable only.
If it points to subclass,

Super super = new Sub();

Narrowing is allowed as in case 1 above.
But if it points to same(super) class, narrowing is not allowed.

Super super = new Super();

So not knowing what the actual case is,compiler does not take any action and leaves it to run time to handle it.

,

Leave a comment

Writing a file in java

Here is the code to write a string to a file in java:

import java.io.*;
class WriteFile {
public static void main(String args[]) {
try{
String s="data to write in file";
File f=new File("a.txt");
FileWriter fwr= new FileWriter(f);
Writer wr= new BufferedWriter(fwr);
wr.write(s);
wr.close();
}
catch(IOException ie) {
System.out.print(ie);
}
catch(Exception e) {
System.out.print(e);
}
}
}

First make a reference to file to which you want to write the data:
File f=new File("a.txt");
Here, in place of .txt, we can use any file extension as .srt,.xml,.doc etc

Then, create a file writer,
FileWriter fwr= new FileWriter(f);

Then, make a writer to write to the file:
Writer wr= new BufferedWriter(fwr);

then, call write function and pass the string:
wr.write(s);
Always remember to close the writer, otherwise it won’t write to the file:
wr.close();

We have to catch the exceptions thrown by the API methods also. To know more about exceptions, go to Java Exceptions

Leave a comment

Making First Character of Every Word in Upper Case and Others in Lower Case in a Java String

Here I am giving a code in java to make first character in upper case and rest in lower case

class UpperFirst
{
static String[] breakAtSpace(String s)
{
int arrayIndex=0;
int first=0;
int last=0;

String arr[]=new String[10];

while(last<s.length())
{
last=s.indexOf(” “,first);
if(last==-1) last=s.length();
arr[arrayIndex]=s.substring(first,last);
first=last+1;
arrayIndex++;
}
return arr;
}

public static void main(String arg[])
{
String s= “here is MY STRING in DiffeRent cAse LetterS”;
String arr[]= UpperFirst.breakAtSpace(s);
StringBuffer result=new StringBuffer(“”);

for(int i=0;i<arr.length;i++)
{
if(arr[i]!=null)
{
String str=arr[i];
for(int j=0;j<str.length();j++)
{
if(j==0) result.append(str.substring(j,j+1).toUpperCase()) ;
else result .append( str.substring(j,j+1).toLowerCase());
}
result.append(” “);
}
}
System.out.print(result);

}

}

The logic I have used is that I have broken the string into words by searching space(” “) character in string. Then stored every word in an array. This is implemented in breakAtSpace() method.
In main method, by checking (j==0), I have changed the first character of every word in upper case and rest in lower case.
the line result.append(" "); appends an space after every word.

The output is:

Here Is My String In Different Case Letters

Leave a comment

Writing/Reading image in java

By using javax.imageio package, we can read/write images. Here is the code:

import java.awt.*;
import javax.swing.*;
import javax.imageio.*;
import java.awt.image.*;
import java.io.*;

public class CropImage extends JFrame {
Image image;
Insets insets;
BufferedImage img = null;

public CropImage() {
super("Crop Image");
ImageIcon icon = new ImageIcon("Sunset.jpg");
//image = icon.getImage();
//image = createImage(new FilteredImageSource(image.getSource(),
//new CropImageFilter(100, 70, 140, 250)));

try {
img = ImageIO.read(new File("Sunset.jpg"));
File outputfile = new File("saved.gif");
ImageIO.write(img, "gif", outputfile);
} catch (IOException e) {
}
}
public void paint(Graphics g) {
super.paint(g);
if (insets == null) {
insets = getInsets();
}
g.drawImage(img, insets.left, insets.top, this);
}
public static void main(String args[]) {
JFrame frame = new CropImage();
frame.setSize(250, 250);
frame.show();
}
}

    Explanation

:java.imageio.ImageIO class has a write method
ImageIO.write(img, "gif", outputfile), which takes the image existing in your system path and writes it to desired image format (gif,png..). To read the image file from the system, use img = ImageIO.read(new File("Sunset.jpg")) which returns a BufferedImage reference.

Instead of using javax.imageio, we can use java.awt.image package also, as shown in commented lines.
ImageIcon icon = new ImageIcon("Sunset.jpg");
image = icon.getImage();
image = createImage(new FilteredImageSource(image.
getSource(),new CropImageFilter(100, 70, 140, 250)));

To paint the image:
g.drawImage(img, insets.left, insets.top, this);

But this way, writing the image is not possible.

Leave a comment

Java Exceptions: Using Exception’s Sub Classes

Syntax of try-catch

try
{
//code which throws some exception
}
catch(XException xe)
{
}
where X is type of exception.

In catch, we have to pass type of exception which is thrown by the code in above try
block.If we know the exact type of excepton thrown, we should use it in catch, as:

catch(SQLException se) {}

But what if we are not sure about type of exception thrown? Here is the solution:

catch(Exception e){}

Exception is superclass of all Exception classes. So a reference of Exception can catch all type of exceptions.
So whatever is the exception type, it will catch it and will not give any error.
To know the type of exception, we can print it:

catch(XException e)
{
System.out.println("Exception type: "+e);
}

Caution: If we are using multiple catch blocks for a single try, always put superclass before subclass, as:

try
{
// code here
}
catch(XException xe){}

catch(Exception e) {}

where XException may be any exception as SQLException,ClassNotFoundException etc.

Putting Exception before XException will produce error.

try
{
// code here
}

// this will give compilation error
catch(Exception e) { }

catch(XException xe) { }

,

Leave a comment