Wednesday, February 3, 2010

tricky question on switch-case

#include
int main()
{
int a=10;
switch(a)
{
case '1': // even if a=1 this case doest not work because it is checking for char '1';
printf("ONE\n");
break;
case '2':
printf("TWO\n");
break;
defa1ut:
printf("NONE\n");
}
return 0;
}

The above program compiles with out any error, but when you run it, it does not give any output

The reason is spelling of key word default is wrong.

Java basic program

Here i am demonstrating a simple program

public class test
{
public static void main(String args[])
{
System.out.println("Hello");
}
}

Save the above file as test.java
Compile the above program: javac test.java
run the program: java test
Output would be: Hello

In Java we write every thing in class. A class should contain a main method which is static and should return void. String args[] is used to take command line arguments.

so far we learned basic program we into some more depth

we will learn different ways of calling a method

public class test
{
public static void main(String args[])
{
int i;
test1 t=new test1(); // creating a instance of test1
i=t.normal(); // calling a method in class test1
System.out.println(i);
}
}
class test1 // this class should not be public
{
public int normal(){
try{
return 10;
}finally{
return 20;
}
}
}

Save the above file as test.java
Compile the above program: javac test.java
run the program: java test
Output would be: 20

Above program we wrote two classes, and accessing a method in one class from another class.

public class test
{
public static int normal(){ // this method should be static
try{
return 10;
}finally{
return 20;
}
}
public static void main(String args[])
{
int i;
test1 t=new test1(); // creating a instance of test1
i=t.normal(); // calling a method in class test1
System.out.println(i);
}
}

Save the above file as test.java
Compile the above program: javac test.java
run the program: java test
Output would be: 20

In the above above program we wrote two methods in one class and both method are static. We made normal method static because we want to access it from main method.