Wednesday, August 26, 2009

Convert int to String in Java Code

Java Code Online is going to discuss the way to convert an int into a String in Java. It is often required in Java programming, to convert an integer into a String value, and operate on it assuming it to be String.

Converting an integer into a String, provides many powerful features and methods which are inherent to Strings, but not to primitives like integer. That make the operating on the value much more easier when the value is used as a String.

I will discuss the most commonly used, and in fact the most easiest and effective method of converting an int into a String.

Use the + operator to convert int to String

1. Use the "+" operator, for converting an int into a String.

Simple isn't it. The logic is that the "+" operator is overloaded in Java. It performs many functions. When used with two integers, it produces the sum. But when a string is used with an int and the "+" operator in between, the the result is a String. For example:-

The issue with + operator for int
Using the + operator with ints result in their addition. The example demonstrates this:-


   package JavaTest1;

    class TestIntToString {

        public static void main(String[] args)

        {
            int i = 2;
            int j = 3;
          
            System.out.println(i + j);
        }
    }


The above code will result in printing 5. This is not what we wanted, so the solution is to use a string in between.

Solution for converting int to String in Java
If we change the above code such that the variable "j" is a String with some String assigned to it. Then the output will be a String. For example:-

    package JavaTest1;

    class TestIntToString {

        public static void main(String[] args)
        {
            int i = 2;
            String j = "";
            int k = 3;

            System.out.println(i + j + k);
        }
    }

When the above code is executed, the the output is:-
    23

So we see that this time the two numbers do not get added, but they resulted in concatenating to each other. This is because they are converted to String. That's really cool. Now this String can use all the methods which are available to Strings. So making it really powerful.

So you can see that by using the "+" operator, you can easily convert an int into a String. I hope the post was helpful to you all. Keep buzzing Java Code Online for more info on Java.

Other Links of interest:-
Convert int to String using Wrapper in Java
Reverse a String
Length of String
Number of words in String
Palindrome Java program

Deadly Diamond of Death

Hearty welcome from Java Code Online. Today's topic is DDD, that is Deadly Diamond of Death. As promised in my earlier post, and as asked by some of my friends in their comments, I will pick this topic to clarify all the myths and doubts. Though the name is Deadly, the topic is not so Deadly, since it is avoided in Java. Java as we all know is a very powerful language. It has all the good features, and avoids all the bad features including the one which will be discussed today.

Java does not support multiple Inheritance. Though it is supported in C++, Java avoids it. The reason for avoiding multiple Inheritance is the Deadly Diamond of Death. Actually the class diagram that is formed in this scenario, is that of a diamond, and it is like a no solution output, so the code gets locked, so it is called Deadly Diamond of death. Thus the Java language do support multiple implementations, but not multiple Inheritance. So a class can implement many Interfaces, but can not extend more than one class.

I will explain the issue by taking an example. Suppose that Java supports multiple inheritance (though it does not, but still we will assume it to understand the current concept). Just go through the following points for a clearer understanding:-

1. Suppose that we have an abstract super class, with an abstract method in it.

2. Now two concrete class extend this abstract super class, and provides the implementation of the abstract method in the super class, in two different ways.

3. Now a fourth class comes into picture which extends the above two concrete classes. So now by the principle of inheritance it inherits all the methods of the parent class, but we have a common method in the two concrete classes but with different implementations, so which implementation will be used for the last child class which inherits both these classes?

Actually no one has got the answer to the above question, and so to avoid this sort of critical issue, Java banned multiple inheritance. The class diagram which is formed above is like that of a diamond, but with no solution or outcome, and so it is called Deadly Diamond of Death.

I will try to make it more clear, by taking an example. Take this:-

// This is our top most abstract class.
class AbstractSuperClass{
abstract void do();
}

// These are the two concrete sub classes which extend the above super class
class ConcreteOne extends AbstractSuperClass{
void do(){
System.out.println("I am going to test multiple Inheritance");
}
}

class ConcreteTwo extends AbstractSuperClass{
void do(){
System.out.println("I will cause the Deadly Diamond of Death");
}
}

// This is our last class which extends both of the above concrete classes
class DiamondEffect extends ConcreteOne, ConcreteTwo{
//Some methods of this class
}




Now what do you think will happen, when an Object of class DiamondEffect is made, and the do method is called?

Since the DiamondEffect class extends both the ConcreteOne and ConcreteTwo classes, it inherits the "do" method from both of them, but the DiamondEffect class does not know which one to use when the method is called on it. The structure of class diagram here is like a diamond. This is the Deadly Diamond of Death.

I hope I was able to make my point clear. If you have any doubts or issues, then do write a comment for me, and I will try my best to answer you. You may leave a comment if you like the article. Java Code Online will see you later in the next post.

Tuesday, August 25, 2009

What are final methods in Java

Hello guys, Java Code Online welcomes you back again, and is going to discuss about the final methods in the Java Programming Language. The Java language provides its users with many resources and tools. There are many features in the Java language that makes it very powerful. Final access modifier is one of those features, that makes Java really solid.

If a method is marked as final, then it implies that it cannot be overridden. So any class that extends the class containing the final methods, cannot override the methods marked final. If any attempt is done to override a final method in a sub class, leads to Java Compiler error.

An example of a final method in a class is:-

/////////////////////////////

class TestFinal{

public final void finalTested(){
//Working of this method
}

//Some other methods

}

/////////////////////////////

The above Java code depicts the use of final when applied to methods.

You may be thinking that what is the advantage of making a method final, though it defies the basic principle of OOPS, that is the final methods are non supportive of inheritance, as they cannot be overridden. It implies that they cannot be extended, and so also makes Polymorphism not feasible for it.

Hmmm... it implies that there are many drawbacks of the final method, but still Java provides it. So there must be some advantage of it also... Lets check them out.

Think of a scenario, that you have made a class, and you want a particular method to be implemented in exactly a particular way, and one should be never allowed to change this implementation. There are many possibilities for it. Like there are many methods in the Java API, which are guaranteed to work in a fixed way, and there is no way we can change them. This scenario calls for marking the method of the class as final. Later I will tell you about the Template Design Pattern which is based on this concept.

I hope you got my point. Whenever you want the methods to be locked, and should not be allowed to be modified, then final is the keyword to be used. The class can still be inherited since it is not marked final, and so the concept of Inheritance and Polymorphism can easily work here, but only for methods which are not marked as final in the super class.

Hope that the article was helpful to you all in understanding the final methods in Java. Keep ticking Java Code Online for more details on Java.

Saturday, August 22, 2009

What is an Interface in Java

Bingo, so we are going to discuss a very important topic today at Java Code Online. Interfaces has been he heart of most of the Java fundamentals and coding, mostly because there existence support Polymorphism, which is one of the four Principle of OOPS apart from Abstraction, Encapsulation and Inheritance.

Interface as the name suggests is a "Contract". Yes you read it right. It is contract between the interface provider and the interface implementer that the methods mentioned in the Interface will be implemented. Mostly Interfaces are used vis a vis Inheritance, and there is much research done before choosing one.

An Interface is like a pure abstract class, with the difference that the all the methods of the interface are abstract, so any class that implements this interface has to implement all the methods mentioned in this interface. That's the law. So actually the interface tells that which methods are to be implemented, but not that how we are going to implement. It is left for the subclasses to decide how to implement this.

One important part of Java is that it supports multiple Implementations, but not multiple Inheritance. So a subclass can implement multiple Interfaces, but cannot extend multiple classes. I will detail on this in a later post where I will tell you that if multiple Inheritance is allowed, then how it may lead to the Deadly Diamond of death. Anyhow that's a bit deviating from the main topic. Our primary concern are the Interfaces.

An example of an Interface is shown below:-

////////////////////////////////////////////

Interface JavaTest{
public static final int val = 3;

public abstract doTest();
public abstract takeResult();
}

////////////////////////////////////////////

Here in this Interface declaration file, the keywords public and abstract are not required for the methods as they are implicit. Moreover the keywords for the variable declared in the Interface are also not required as they are also implicit.

So any variable declared in an Interface is practically a constant, and all the methods which are declared in the interface have to be implemented by the first concrete subclass that implements this interface.

There is one key point regarding the Interfaces, and that is you cannot declare the methods of the Interface to be final. Remember that final methods cannot be overridden, and an abstract method is useless if we do not override it. That is the main reason that abstract and final are never used together for any method.

I hope the article was helpful in understanding the Interface in Java. Do post a comment if you liked the article. For more Java info Java Code Online is the key.

Java Code for File Extension

Hi friends, Java Code Online welcomes you back again. The last post I have made was for getting the file name without the extension of the file. But there are many scenarios when we desire the extension of the file, and not the name of the file.

The Java code here asks the user to enter a valid file name, and then remove the file name but keep the extension of it. So the user enters a file name and gets the extension of it.

The Java Code is provided below:-

///////////////////////////////////
package developer;

import java.util.Scanner;

public class FileExtension {

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

String fileExt = null;

System.out.println("Enter a valid file name whose extension is desired:");

Scanner scan = new Scanner(System.in);

if(scan.hasNext())
{
fileExt = getFileExtension(scan.next());
}

if(null != fileExt)
{
System.out.println("The extension of the file is: "+fileExt);
}
else
{
System.out.println("Not a valid file name");
}

}

//get the file extension of the file entered
public static String getFileExtension(String filePath)
{
String extension = null;
if(null != filePath && filePath.contains("."))
{
extension = filePath.substring(filePath.lastIndexOf("."), filePath.length());
}
return extension;
}

}

////////////////////////////////////////

When this code is executed, the output is something like as given below:-

//////////////////////////////////////////
Output

Enter a valid file name whose extension is desired:
javadeveloper.java
The extension of the file is: .java
/////////////////////////////////////////

I hope the article was helpful, and my efforts did not went in vain. Keep ticking Java Code Online for more Java details.

Other article of interest:-
Remove the extension from the filename

Remove Extension of File Java Code

Hello friends, welcome once again at Java Code Online. The topic of the day is the Java code that helps in removing the extension of a file name that is entered by the user.

The operation is a simple one and is crucial in case of file handling. Though mostly we need to remove the file extension before processing the file, there may be other requirements that ask for this requirement.

Anyhow the Java Code is provided below:-

//////////////////////////////

package developer;

import java.util.Scanner;

public class RemoveFileExtension {

public static void main(String[] args) {

String fileRemExt = null;

System.out.println("Enter a valid file name whose extension is to be removed:");

Scanner rem = new Scanner(System.in);

if(rem.hasNext())
{
fileRemExt = removeFileExtension(rem.next());
}

if(null != fileRemExt)
{
System.out.println("The file name without extension is: "+fileRemExt);
}
else
{
System.out.println("Not a valid file name");
}

}

//remove the file extension of the file entered
public static String removeFileExtension(String fileName)
{
if(null != fileName && fileName.contains("."))
{
return fileName.substring(0, fileName.lastIndexOf("."));
}
return null;
}

}
////////////////////////////////////

Once this code is executed, the output is something like:-

////////////////////////////////////
Output

Enter a valid file name whose extension is to be removed:
test.java
The file name without extension is: test
////////////////////////////////////

I hope the article was helpful to most of you. In case you liked the article then do leave a comment at Java Code Online.

Thursday, August 20, 2009

Anonymous Inner Class in Java

Hi everybody, Java Code Online is going to discuss the Anonymous Inner Class in Java today. This class as the name specifies is not named. It means that this class has a body but no name. And so it is anonymous.

It is one of the most bizarre type of Inner class. It is always invoked from outside the Outer class. When the invocation is done, then this class is placed after the brackets of the method invocation. The key to understand this is that, actually the Anonymous inner class always extend or implement, but not both at the same time.

When the Outer class is invoked, then the syntax is something like:-

OuterClass oc = new OuterClass();

But when the anonymous inner class comes into picture the code is something like:-

OuterClass oc = new OuterClass(){
//some inherited method
};

The syntax though very much strange is the correct one. Here the curly braces after the instantiation call infact causes an anonymous inner class to be formed which either inherits or implements the method of the instantiated class. So the only methods available here are the one by inheritance or implements. Note the semicolon at the end of the curly braces, strange but true. Here the main concept is of Polymorphism as the name of the super class is used to refer the sub class, which is our anonymous inner class in this case.

For reference,
Types of Inner Class
1. Regular Inner Class
2. Method Local Inner Class
3. Anonymous Inner Class
4. Static Nested Inner Class

Hope that the article helped solved your issues with this type of class. Remember Java Code Online is the key to a vast pool of Java. That's it for now. See you later.

Method Local Inner Class in Java

Hello and welcome back to Java Code Online. Today I will be discussing about the Method Local Inner Class in Java. It is one of the four subtypes of Inner Classes.

The Method Local Inner class, as the name specifies is local to a method. It implies that the method local Inner class is defined inside a method of a class. As the class is defined inside a method, it needs to be instantiated from with in the same method, but after the class definition is finished. As a mater of fact this inner class cannot use the variables of the same method, unless they are declared final.

If you did not instantiate the class within the same method and after the class definition is finished, then that inner class though valid will be useless, as there is no other way to instantiate it. Moreover the Instantiation must be after the class definition or else the Java Compiler will not be able to see it.

Hoping that this article was helpful to you all. Do post a comment if you liked this article.

For reference,
Types of Inner Class
1. Regular Inner Class
2. Method Local Inner Class
3. Anonymous Inner Class
4. Static Nested Inner Class

Keep buzzing Java Code Online for more Java Information.

Static Inner Nested Class in Java

Hi friends, welcome back to Java Code Online. This article is in continuation to the previous article on Regular Inner Class, here I will discuss the second type of Inner Class called Static Inner Nested Class.

The static Inner Nested Classes are nothing else, but are like Regular Inner class, but are marked static. So the behavior of these classes is static in nature. This explains most of the behavior of the static inner class. Like it behaves like a class level variable. I mean to say that, you need not instantiate the outer class for creating an instance of the static inner class, and that the static inner class can be directly instantiated.

Moreover as the behavior of a static member is, the static inner class cannot access the non static members of the class, this is in sync with the basic properties of a static variable or member of a class. For instantiating a Static Inner Class, you need to use the name of both the Outer class and Inner class. For example:-

OuterClass.InnerClass ocic = new OuterClass.InnerClass();

I hope the article was helpful. In case it was, the do leave a comment.

For reference,
Types of Inner Class
1. Regular Inner Class
2. Method Local Inner Class
3. Anonymous Inner Class
4. Static Nested Inner Class

Keep checking Java Code Online for more Java info.

You might be interested in these too:-
Static Inner Class Example in Java

Regular Inner Class in Java

Hi friends, welcome back to Java Code Online. Today's article discuss the regular inner class in Java. Though the inner classes could be classified in 4 sub types, regular inner classes is the most commonly used sub type.

The regular inner class is a full fledged member of the outer class, so it shares all the features of a member of a class. Like an Inner class has access to all the variable of the outer class including the private variables. There is a special way to instantiate an Inner class. For instantiating a regular Inner Class, you need to instantiate the Outer class first.

If you are invoking the regular inner class from inside the Outer class, then it could be instantiated like a regular class, like:-

InnerClass ic = new InnerClass();

But if the Inner class needs to be instantiated from outside the Outer class, then first you need to get a reference of the Outer class Object, and then create an Object of the Inner class from that. The syntax is something like given below:-

OuterClass oc = new Outer Class();
OuterClass.InnerClass ic = oc.new InnerClass();

I hope that this article was helpful in clearing all your doubts about Regular Inner Classes.

For reference,
Types of Inner Class
1. Regular Inner Class
2. Method Local Inner Class
3. Anonymous Inner Class
4. Static Nested Inner Class

For more information on Java, keep buzzing Java Code Online.

Types of Inner Class in Java

Hi friends, Java Code Online welcomes you back again. Today's article discuss the Inner classes in Java. An Inner class is like a class but it is defined inside another class. So the behavior is like of a class but is internal to a class.

The Inner Classes can be classified in four types. They are:-
1. Regular Inner Class
2. Method Local Inner Class
3. Anonymous Inner Class
4. Static Nested Inner Class

All the types of inner classes are defined in their respective articles. The Inner classes though not much commonly used in Java, still find some important place in some programs. Though it is a bit too odd to see a class being placed inside another class, the behavior is more or less like a local method of the outer class. There is different functionality for all the different types of Inner classes. You may find the details in the individual articles for each type of Inner class.

I hope the article was able to clear your myth and doubts about the Inner classes in Java. If you liked the article then do leave a comment. Keep buzzing Java Code Online for more Java articles.

Wednesday, August 19, 2009

Armstrong Number Java Program

Hello, welcome back to Java Code Online. Today I would be discussing an important mathematical Java Code. This Java Code is for Armstrong Number. The code asks the user to enter a number, and then checks that whether it is Armstrong Number or not.

An Armstrong Number is one in which the sum of the individual numbers raised to the power of the number of words in that number is equal to that particular number itself. For example 1 raised to the power 1 is equal to 1, so it is an Armstrong Number. Again 153, implies 1 raised to the power 3, 5 raised to the power 3, and then 3 raised to the power 3 are added, then it gives 153 again, so it is also an Armstrong Number.

The Java Code is given below:-

////////////////////////////////////

package developer;

import java.util.Scanner;

public class ArmstrongNumber {

static double finalValue = 0;

public static void main(String[] args) {

int valueTaker = 0;

System.out.println("Enter a number to be checked for Armstrong Number: ");

Scanner armstScan = new Scanner(System.in);

if(armstScan.hasNextInt())
{
valueTaker = armstScan.nextInt();
}

StringBuffer sb = new StringBuffer().append(valueTaker);

double lengthSBKeeper = sb.length();

for(int lengthKeeper = 0; lengthKeeper < sb.length(); lengthKeeper++)
{
double zxc = Integer.parseInt(sb.substring(lengthKeeper, lengthKeeper+1));

finalValue = Math.pow(zxc, lengthSBKeeper) + finalValue;

}

if(finalValue == valueTaker)
{
System.out.println("The entered number "+valueTaker+" is an Armstrong Number");
}
else
{
System.out.println("The entered number is not an Armstrong Number");
}
}
}

///////////////////////////////////////

I hope the code above was helpful to all of you. Just copy the code in your IDE, and change the package name accordingly, and you are set to roll. Keep buzzing Java Code Online for more Java information.

Other Java Programs that might be of some interest:-
Factorial Program in Java
Palindrome Program in Java
Prime Number Program in Java
Fibonacci Series Program in Java

Difference ArrayList and Array in Java

Welcome back again on Java Code Online. Today I would be discussing the main difference between an ArrayList and an Array in Java.

In Java an Array is always of fixed size. The size has to be defined at the initializing time of the array. The number of the rows is a must for any array, though the number of columns may be specified later. By using Array, there is comparatively less flexibility, as the size need to be known before hand. And if you initialize an array that is too long, then it results in wastage of precious memory of the heap. The Garbage Collector then has a tough time maintaining the memory for other resources.

On the other hand, the ArrayList is dynamic in nature. It provides for automatic resizing of the List. Moreover you need not specify the size at the beginning of the initialization part. The ArrayList is therefore much more widely used as compared to an Array in Java. ArrayList is and extension of the List Interface. So it is a part of the Collections framework.

Talking about the drawbacks of ArrayList, then there is probably only one, and that is typecasting. When an Object is added to an ArrayList it goes inside as an Object, and so when it is retrieved back, then it needs to be typecast back into the original Object.

The Arrays have a positive point in this regard, that is an array is always of a particular type that is an array of ints, or an array of Strings, etc. So when data is retrieved back from an Array, then no typecasting is required.

More or less the advantages of an ArrayList makes it one of the most versatile and important tool in the Java coding, and arrays are left far behind in the race of fame.

Keep buzzing Java Code Online for more info on Java.

Addition of two numbers Java Program

Hello all of you. Welcome back to Java Code Online. Today I will be giving you a very simple and basic program of Java, that is the addition of two numbers. The code makes use of Scanner for getting the input from the console.

The code starts by asking the user to enter two numbers to be added. The user enters the first number, press enter, and then enters the second number and then press enter again. After this the code computes the addition of these two numbers.

The Java Code is provided below:-

//////////////////////////////////////

package developer;

import java.util.Scanner;

public class AddTwoNumber {

/**
* @param args
*/
public static void main(String[] args) {
System.out.println("Enter the first and second numbers");
//Get the first number
Scanner scanOne = new Scanner(System.in);
//Get the second number
Scanner scanTwo = new Scanner(System.in);

if(scanOne.hasNextInt() && scanTwo.hasNextInt())
{
System.out.print("The sum of the two numbers entered is: ");
System.out.println(scanOne.nextInt()+scanTwo.nextInt());
}

}

}

//////////////////////////////////////////

I hope that this basic code was beneficial for the beginners to Java Programming. For more information and programs on Java, keep buzzing Java Code Online.

Related Programs
Hello World Program in Java
Length of a String Java Program
Palindrome Program in Java

Tuesday, August 18, 2009

Factors of a number Java Program

Hi all of you. The following article at Java Code Online is going to discuss the code for finding the factors of a number entered by the user. The Java Program starts by prompting the user to enter a number, and then displays the all the factors of the number entered by the user.

The factors of a number are the numbers which divide the number entered by the user completely.

The Java Example Code is given below:-

/////////////////////////////////////////

package developer;

import java.util.Scanner;

public class Factor {

/**
* @param args
*/
public static void main(String[] args) {
System.out.println("Enter a number whose factors are desired: ");
Scanner scanNum = new Scanner(System.in);
int numFac = 0;
if(scanNum.hasNextInt())
{
numFac = scanNum.nextInt();
}

System.out.println("The Factors of the entered number are:-");

for(int i = 1; i <= numFac; i++)
{
if(numFac%i == 0)
{
System.out.print(i+" ");
}
}

}

}

/////////////////////////////////////////

The Java Code above finds all the factors of the number entered by the user. For more interesting information on Java, keep checking Java Code Online.

Related links:-

Prime Factors Java Program
Factorial of a Number Java Program

Prime Factors Java Program

Hello all of you. Today at Java Code Online, I would be discussing the Java Code for finding all the prime factors of an entered number.

Prime Factors are those numbers which are factors of the entered number, and also are Prime in nature. For being a factor, the number needs to divide completely the entered number. For example, f I say that the user entered 20, then the factors of this number are 1 2 4 5 10 and 20, but when we say about Prime Factors then out of these only 2 and 5 are prime, so 2 and 5 are the Prime factors of the number 20 which is entered by the user.

The complete Java code is given below:-

////////////////////////////////////////

package developer;

import java.util.Scanner;

public class PrimeFactor {

static int primeCheck = 1;

public static void main(String[] args) {
System.out.println("Enter a number whose Prime factors are desired: ");
Scanner numS = new Scanner(System.in);
int numPriFac = 0;
if(numS.hasNextInt())
{
numPriFac = numS.nextInt();
}

System.out.println("All the Prime Factors of the entered number are:-");

for(int tap = 1; tap <= numPriFac; tap++)
{
if(numPriFac%tap == 0)
{
for(int primeTest = 2; primeTest < tap; primeTest++)
{
if(tap%primeTest == 0)
{
primeCheck = 1;
break;
}
else
{
primeCheck = 0;
}
}
if(primeCheck == 0 || tap == 2)
{
System.out.print(tap+ " ");
}
}
}
}
}

///////////////////////////////////////////

I hope the code was helpful to all of you. Java Code Online keeps on discussing various Java codes, so keep checking for new updates.

Related Links:-
Prime Number program in Java
Largest Prime number Java Program
Smallest Prime Number Java Program
Prime Number Series Java Program

Monday, August 17, 2009

Prime Number Series Java Program

Hi friends, welcome back to Java Code Online. Today I will be discussing the Java Code to generate a series of Prime Numbers. The series of Prime Numbers all the Prime numbers which are less then the number provided by the user.

The Java Code starts by asking the user to enter a number, and then displays all the Prime Numbers which are less then or equal to that number. This program generates all the prime numbers less then a number, so it is a series of Prime Numbers.

The Java Code is provided below:-

///////////////////////////////////////

package developer;

import java.util.Scanner;

public class PrimeNumberSeries {

public static void main(String[] args)
{
int numero = 0;
System.out.println("Enter a number:");
Scanner takeValue = new Scanner(System.in);
if(takeValue.hasNextInt())
{
numero = takeValue.nextInt();
}
System.out.println("All the Prime Numbers, which are less then or equal to the number entered are:");
checkPrimeNumber(numero);
}

static void checkPrimeNumber(int val)
{
int tapper = 0;

for (int i=2; i < val; i++ ){
if(val%i == 0)
{
tapper = 0;
break;
}
else
{
tapper = 1;
}
}
if(tapper == 1 || val == 2)
{
System.out.print(val+" ");
if(val > 2)
checkPrimeNumber(val-1);
}
else
{
if(val > 2)
checkPrimeNumber(val-1);
else
System.out.println("Number out of range");
}
}
}

///////////////////////////////////////////////

I hope the Java Code was helpful to you all. Keep buzzing Java Code Online, for more info on Java.

Related Java Programs
Prime Number program in Java
Largest Prime number Java Program
Smallest Prime Number Java Program

Sun Certified Java Programer (SCJP) Syllabus

Hi friends, today at Java Code online, I would be giving you the syllabus for SCJP 6.0, SCJP stands for Sun Certified Java Programmer. The exam is a very prestigious exam, and clearing the exam implies acknowledgment in the elite class of SCJP certified professionals.

The SCJP 6.0 Exam Objectives are given below:-

Section 1: Declarations, Initialization and Scoping

* Develop code that declares classes (including abstract and all forms of nested classes), interfaces, and enums, and includes the appropriate use of package and import statements (including static imports).
* Develop code that declares an interface. Develop code that implements or extends one or more interfaces. Develop code that declares an abstract class. Develop code that extends an abstract class.
* Develop code that declares, initializes, and uses primitives, arrays, enums, and objects as static, instance, and local variables. Also, use legal identifiers for variable names.
* Given a code example, determine if a method is correctly overriding or overloading another method, and identify legal return values (including covariant returns), for the method.
* Given a set of classes and superclasses, develop constructors for one or more of the classes. Given a class declaration, determine if a default constructor will be created, and if so, determine the behavior of that constructor. Given a nested or non-nested class listing, write code to instantiate the class.



Section 2: Flow Control

* Develop code that implements an if or switch statement; and identify legal argument types for these statements.
* Develop code that implements all forms of loops and iterators, including the use of for, the enhanced for loop (for-each), do, while, labels, break, and continue; and explain the values taken by loop counter variables during and after loop execution.
* Develop code that makes use of assertions, and distinguish appropriate from inappropriate uses of assertions.
* Develop code that makes use of exceptions and exception handling clauses (try, catch, finally), and declares methods and overriding methods that throw exceptions.
* Recognize the effect of an exception arising at a specified point in a code fragment. Note that the exception may be a runtime exception, a checked exception, or an error.
* Recognize situations that will result in any of the following being thrown: ArrayIndexOutOfBoundsException,ClassCastException, IllegalArgumentException, IllegalStateException, NullPointerException, NumberFormatException, AssertionError, ExceptionInInitializerError, StackOverflowError or NoClassDefFoundError. Understand which of these are thrown by the virtual machine and recognize situations in which others should be thrown programatically.



Section 3: API Contents

* Develop code that uses the primitive wrapper classes (such as Boolean, Character, Double, Integer, etc.), and/or autoboxing & unboxing. Discuss the differences between the String, StringBuilder, and StringBuffer classes.
* Given a scenario involving navigating file systems, reading from files, writing to files, or interacting with the user, develop the correct solution using the following classes (sometimes in combination), from java.io: BufferedReader, BufferedWriter, File, FileReader, FileWriter, PrintWriter, and Console.
* Use standard J2SE APIs in the java.text package to correctly format or parse dates, numbers, and currency values for a specific locale; and, given a scenario, determine the appropriate methods to use if you want to use the default locale or a specific locale. Describe the purpose and use of the java.util.Locale class.
* Write code that uses standard J2SE APIs in the java.util and java.util.regex packages to format or parse strings or streams. For strings, write code that uses the Pattern and Matcher classes and the String.split method. Recognize and use regular expression patterns for matching (limited to: . (dot), * (star), + (plus), ?, \d, \s, \w, [], ()). The use of *, +, and ? will be limited to greedy quantifiers, and the parenthesis operator will only be used as a grouping mechanism, not for capturing content during matching. For streams, write code using the Formatter and Scanner classes and the PrintWriter.format/printf methods. Recognize and use formatting parameters (limited to: %b, %c, %d, %f, %s) in format strings.



Section 4: Concurrency

* Write code to define, instantiate, and start new threads using both java.lang.Thread and java.lang.Runnable.
* Recognize the states in which a thread can exist, and identify ways in which a thread can transition from one state to another.
* Given a scenario, write code that makes appropriate use of object locking to protect static or instance variables from concurrent access problems.



Section 5: OO Concepts

* Develop code that implements tight encapsulation, loose coupling, and high cohesion in classes, and describe the benefits.
* Given a scenario, develop code that demonstrates the use of polymorphism. Further, determine when casting will be necessary and recognize compiler vs. runtime errors related to object reference casting.
* Explain the effect of modifiers on inheritance with respect to constructors, instance or static variables, and instance or static methods.
* Given a scenario, develop code that declares and/or invokes overridden or overloaded methods and code that declares and/or invokes superclass, or overloaded constructors.
* Develop code that implements "is-a" and/or "has-a" relationships.



Section 6: Collections / Generics

* Given a design scenario, determine which collection classes and/or interfaces should be used to properly implement that design, including the use of the Comparable interface.
* Distinguish between correct and incorrect overrides of corresponding hashCode and equals methods, and explain the difference between == and the equals method.
* Write code that uses the generic versions of the Collections API, in particular, the Set, List, and Map interfaces and implementation classes. Recognize the limitations of the non-generic Collections API and how to refactor code to use the generic versions. Write code that uses the NavigableSet and NavigableMap interfaces.
* Develop code that makes proper use of type parameters in class/interface declarations, instance variables, method arguments, and return types; and write generic methods or methods that make use of wildcard types and understand the similarities and differences between these two approaches.
* Use capabilities in the java.util package to write code to manipulate a list by sorting, performing a binary search, or converting the list to an array. Use capabilities in the java.util package to write code to manipulate an array by sorting, performing a binary search, or converting the array to a list. Use the java.util.Comparator and java.lang.Comparable interfaces to affect the sorting of lists and arrays. Furthermore, recognize the effect of the "natural ordering" of primitive wrapper classes and java.lang.String on sorting.



Section 7: Fundamentals

* Given a code example and a scenario, write code that uses the appropriate access modifiers, package declarations, and import statements to interact with (through access or inheritance) the code in the example.
* Given an example of a class and a command-line, determine the expected runtime behavior.
* Determine the effect upon object references and primitive values when they are passed into methods that perform assignments or other modifying operations on the parameters.
* Given a code example, recognize the point at which an object becomes eligible for garbage collection, determine what is and is not guaranteed by the garbage collection system, and recognize the behaviors of the Object.finalize() method.
* Given the fully-qualified name of a class that is deployed inside and/or outside a JAR file, construct the appropriate directory structure for that class. Given a code example and a classpath, determine whether the classpath will allow the code to compile successfully.
* Write code that correctly applies the appropriate operators including assignment operators (limited to: =, +=, -=), arithmetic operators (limited to: +, -, *, /, %, ++, --), relational operators (limited to: <, <=, >, >=, ==, !=), the instanceof operator, logical operators (limited to: &, |, ^, !, &&, ||), and the conditional operator ( ? : ), to produce a desired result. Write code that determines the equality of two objects or two primitives.

This syllabus and exam Objective can be viewed at Sun Official site.

Preparing for the SCJP exam provides an oppurtunity to strength your Java Concepts. It makes your programming skills established in front of the world, and also is helpful in building confidence for the Java Interviews.

I hope the syllabus provided was helpful to you all. For more info on Java keep buzzing Java Code Online.

Related article
Sun Certified Java Programmer SCJP

Sunday, August 16, 2009

Smallest Prime Number Java Program

Hi friends, today Java Code Online will be discussing the Java code for finding the smallest Prime number, which is greater then the number provided by the user.

The Java code starts by asking the user to enter a number, and then it generates the smallest Prime number which is greater then the user provided number.

The Java Code is given below:-

////////////////////////////////////

package developer;

import java.util.Scanner;

public class SmallestPrime {

public static void main(String[] args)
{
int num = 0;
System.out.println("Enter a number:");
//get the input from the console
Scanner scan = new Scanner(System.in);
if(scan.hasNextInt())
{
num = scan.nextInt();
}
checkPrime(num);
}

static void checkPrime(int num)
{
int check = 0;

for (int i=2; i < num; i++ ){
if(num%i == 0)
{
check = 0;
break;
}
else
{
check = 1;
}
}
if(check == 1 || num == 2)
{
System.out.println("The smallest prime number which is greater then or equal to the number provided is: "+num);
}
else
{
if(num > 0)
checkPrime(num+1);//Recursion in use
else
System.out.println("Number out of range");
}
}
}
////////////////////////////////

Hope that the provided Java code was beneficial to you all. Keep checking Java Code Online for more info on Java.

Related Programs
Prime Number program in Java
Largest Prime number Java Program

Largest Prime Number Java Program

Hi friends, welcome back to Java Code Online. Today I will be discussing the Java Code, to find the largest prime number, which is smaller then the number provided by the user.

A prime number is a positive integer which is divisible by 1 and itself only. The Java Code for finding the largest Prime number which is lower then the number provided by the user is given below:-

///////////////////////////////////
package developer;

import java.util.Scanner;

public class LargestPrime {

public static void main(String[] args)
{
int num = 0;
System.out.println("Enter a number:");
Scanner scan = new Scanner(System.in);
if(scan.hasNextInt())
{
num = scan.nextInt();
}
checkPrime(num);
}

static void checkPrime(int num)
{
int check = 0;

for (int i=2; i < num; i++ ){
if(num%i == 0)
{
check = 0;
break;
}
else
{
check = 1;
}
}
if(check == 1 || num == 2)
{
System.out.println("The largest prime number which is less then or equal to the number provided is: "+num);
}
else
{
if(num > 2)
checkPrime(num-1);
else
System.out.println("Number out of range");
}
}
}
//////////////////////////////

I hope the above Java code was helpful to you all. For more info on Java keep buzzing Java Code Online.

Related Java Programs
Prime Number program in Java

Floyd Triangle Program in Java

Welcome back again, today at Java Code Online, I would be discussing the Java code for Floyd's Triangle.

The Floyd's triangle starts from 1, it is a right angled triangle, consisting of consecutive numbers. If suppose four rows of the Floyd's Triangle need to be generated, then the output will be, the first row contains 1, the second row contains 2 3, the third row contains 4 5 6, and the last row contains 7 8 9 10. I hope that will clear your concept about the Floyd's Triangle. One more intresting fact about this triangle is that all the last numbers of each row are Triangular numbers.

The Java Code provided, asks the user to enter the number of rows till which the Floyd's Triangle is desired, and then generates it. The Java Program is given below:-

package developer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class FloydTriangle {

static int counter = 0;
/**
* @param args
* @throws IOException
* @throws NumberFormatException
*/
public static void main(String[] args) throws NumberFormatException, IOException {
System.out.println("Enter the number of rows for Floyd Triangle:");
InputStreamReader ir = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ir);


int num = Integer.parseInt(br.readLine());

for(int i = 1; i <= num; i++)
{
for(int j = 1; j <= i; j++)
{
counter = counter + 1;
System.out.print(counter);
System.out.print(" ");
}
System.out.println("");
}

}
}

I hope that this post was helpful to you all. Kindly leave your comments in case you liked the above code. For more info on Java, keep buzzing Java Code Online.

Triangular Number Program in Java

Hi friends, today Java Code Online is going to discuss the Java Code for generating the Triangular Numbers up to the entered number of times.

A Triangular Number is one which is the sum of all the numbers starting from 1 up to that particular number. For example if I say the number is 3, then 1+2+3=6, so 6 is the third Triangular Number.

The provided Java code asks the user, to enter the required number of Triangular Numbers, and then generate that many Triangular Numbers starting from 1.

The Java Code is provided below:-

package developer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class TriangularNumber {

/**
* @param args
* @throws IOException
* @throws NumberFormatException
*/
public static void main(String[] args) throws NumberFormatException, IOException {
System.out.println("How many Triangular Numbers are required:");
InputStreamReader ir = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ir);
int j = 1;
int num = Integer.parseInt(br.readLine());

for(int i = 1; i<= num; i++)
{
j = i * (i+1)/2;
System.out.print(j + " ");
}
}
}

I hope the above Java Code was helpful to you all. Keep buzzing Java Code Online for more interesting Java information and programs.

Pascal Triangle in Java

Hi friends, today at Java Code Online, I am going to discuss a very interesting yet basic Java program, that displays the Pascal Triangle for any given integer value.

A Pascal Triangle is a triangle in which a triangle is formed of numbers, in which 1 is displayed one time, 2 is displayed two times, 3 is displayed three times, and so on, up to the entered value of the integer value. Each of these different numbers are displayed on different lines, but the same number is displayed on the same line. The whole structure is in the form of a triangle, and it is called Pascal Triangle.

The Java Code is provided below, the code asks the user to enter a number, and then prints the Pascal Triangle up to that many rows:-

 package developer;

 import java.io.BufferedReader;
 import java.io.IOException;
 import java.io.InputStreamReader;

 public class Pascal {
    public static void main(String[] args) throws IOException {
        System.out.println("Enter the number of rows for which the Pascal Triangle is requird: ");
        InputStreamReader is = new InputStreamReader(System.in);
        BufferedReader bf = new BufferedReader(is);
        int numRow = Integer.parseInt(bf.readLine());

        for (int i = 1; i <= numRow; i++) {
            // Prints the blank spaces
            for (int j = 1; j <= numRow - i; j++) {
                System.out.print(" ");
            }
            // Prints the value of the number
            for (int k = 1; k <= i; k++) {
                System.out.print(i + " ");
            }
            System.out.println();
        }
    }
 }


I hope the above code was helpful to you all. For more information on Java, you know that Java Code Online is the place you need to be at.

Other Java Programs that might be of interest:-
Palindrome Program in Java
Factorial Program in Java
Fibonacci Series Program in Java
Prime Number Program in Java
String In Java

Friday, August 14, 2009

Palindrome Java Program

Hi friends, welcome back to Java Code Online. Today I will be discussing the Java Program to find out whether any entered String or number or any combination of them is a Palindrome or not.

A Palindrome is a string or number, that is exactly the same when it is read in the reverse order. That is for example "anna" is a palindrome, i.e. read the same either way.

The Java code for finding the Palindrome is given below:-

//////////////////////////////
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class Palindrome {

/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
System.out.println("Enter a number or String to be checked for Palindrome");
InputStreamReader io = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(io);
String num = br.readLine();
StringBuffer num2 = new StringBuffer().append(num);
if(num.equals(num2.reverse().toString()))
{
System.out.println("It is a Palindrome");
}
else
{
System.out.println("It is not Palindrome");
}

}

}
/////////////////////////////

I hope the Java code provided for finding the Palindrome was helpful to you all. For more info on Java, keep checking Java Code Online.

Number of words in a String - Java Program

Hi friends, welcome back to Java Code Online. Today I will discuss a simple Java Program to find the number of words in any String entered by the user. The Java application starts by asking the user to enter a String, and then finds the number of words in that String.

The Java Code is displayed below for reference:-


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class NoOfWordsInString {

public static void main(String[] args) throws IOException {
System.out.println("Enter a string or number for which the number of words is to be counted: ");
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String str = br.readLine();
System.out.println("The no of words in the string are: "+str.length());
}
}

I hope the Java code above was helpful to you all, for more info on Java keep buzzing Java Code Online.

Related Java Programs
Reverse Java String
Length of a String

Sunday, August 9, 2009

Desending Sort - Java Program

Hi friends, welcome back to Java Code Online. Today I will discuss the Java Program for sorting an array of numbers in descending order. It is similar to the previous Java program I discussed for ascending sort.

The strong point of this Java code is that, we make use of TreeSet Collection for sorting the array in reverse order. The Java code is provided below:-


import java.util.TreeSet;


public class SortingDescending {

@SuppressWarnings("unchecked")
public static void main(String[] args) {
int[] num = {3,5,9,2,1,0,45,23,67,93};
TreeSet ts = new TreeSet();

for(int i = 0; i < num.length; i++)
{
ts.add(num[i]);
}
System.out.println("The numbers of the array in descrending order are: "+ts.descendingSet());
}
}


I hope the Java Code provided was helpful to you all. For more info on Java, keep buzzing Java Code Online.