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

This post is part of Java Tutorial. This post is applicable for all people who are following Java Tutorial.Today we are going to discuss various control flow statements available in Java.

In Java ( also in C,C++) the flow of control is sequential. I mean statements are executed line by line. After the execution of first statement, control goes to second statement and then third and so on. The program will be terminated after the execution of last statement. So statements are executed from top to bottom.

Some times we need to break up the flow of execution. We need to execute first statement and then based on certain condition we may go for second statement or we can directly jump to sixth statement. To do this type of task control flow statements are there in Java.

Control flow statements break up the flow of execution by employing decision making, looping, and branching. In Java decision making statements are if, else, switch, the looping statements are for, while, do-while, and the branching statements are break, continue, return.

if statement:
Using if we can execute a statement (or block of statements) based on the condition specified using if. If the condition is true then only the block of statements will be executed. Otherwise the block will be simply skipped.

Syntax of if statement:

if(condition)
{ // block start

//executable statement1
//executable statement2

// block end
}
Note that { } (curly braces) are not necessary if there is only one statement in the block.

Syntax of if-else statement:

if(condition)
{ // block start

//executable statement1
//executable statement2

// block end
}
else
{ // block start

//executable statement3
//executable statement4

// block end
}
Like this we can also define another ‘if’ after the ‘else’ part. This is termed as nested if.

switch statement:
switch works similar to if-else statements. It provides better readability as compared to if-else. The General Syntax of switch is:

switch(variable)
{

case value1: // code to be executed;
break;
case value2: // code to be executed;
break;
.
.
.
default : //code to be executed;

}
In switch the variable is matched with corresponding value. If any matching value is found, that case will be executed. Observe we have given break keyword after every case. This is necessary otherwise all the cases after the matching case will get executed. The keyword break is used here to transfer the control outside of switch once our code has been executed.

Keyword default will only get executed if all the cases fails to execute. That means if none of the cases match then only default case will be executed. Default can be present any where in the switch block but it will always get executed after testing all the cases. Generally people use to write default as the last choice in the switch block. Also default is optional in switch.

while statement:
Some times we need to execute a set of statements continuously as long as the condition is true. To do such type of tasks we have while statement.

The syntax of while statement is:

while(condition)
{

executable code;
.
.
.
}
As long as the condition specified with in while loop is true the block of code will get executed. If the condition becomes false the loop will be skipped. We have to write code in the while block in such a way that every time the loop comes closer to the breaking condition. Otherwise the loop will not be terminated at all. such type of loops are known as infinite loops. Remember in while loop if the condition evaluates to false at first time then the block of code will not be executed at all. This is also known as entry control loop.

do-while statement:
Do while loop is also similar to while loop except one difference. In do-while loop the condition is tested at bottom instead of at top.

The syntax of do- while statement is:

do
{

executable code;
.
.
.
} while(condition);
Since the condition is tested at bottom even though it evaluates to false the loop will be executed at least once. Hence it is also known as exit control loop. Also observe after do while condition semicolon is necessary.

Here is another puzzle for Java programmers. Previously I posted a puzzle related to Java. Here is the solution for the Puzzle to print output as Sun Java Programmer.

Our new puzzle is you have to print the output of a Java program which contains all the source code written by you. That means whatever code you are going to write that should be printed as output.

One more point here to note is you are not allowed to use Files concept to solve this puzzle. The exact copy of source code should be printed as output of the program.

Solution:




public class N { public static void main(String [] args) { char c=34; System.out.println(s+c+s+c+';'+'}'); }

static String s="public class N { public static void main(String [] args){ char c=34;System.out.println(s+c+s+c+';'+'}');}  static String s=";
}

Copy the above code in a notepad file and save it as N.java. Compile and run the file and see the output .

Share the code with your friends if you like it.

Welcome again to Java session after a long gap. In today’s session we are going to deal with various types of operators in Java.

Let us assume one statement c=a+b. In the above statement we can say that variables a,b and c are operands. Whereas + and = are operators.

An operator is a one which is going to perform some action on operands.

Here + is used to add a and b and again = is used to assign the result to variable c.

But here there is a catch. In mathematics some times we may even write a+b=c and c=a+b but in Java you are not supposed to write a+b=c because a+b contains some value. And we cannot assign some variable to value. But we can assign a value to a variable. I mean c=a+b is just fine. I think this is clear to you.

Arithmetic Operators:

Java programming language provides operators that perform addition, subtraction, multiplication, and division. These operators are similar to the operators found in basic mathematics. The only symbol that might look new to you is %, which divides one operand by another and returns the remainder as its result.

+ (Addition Operator, also used to add two strings)
- (Subtraction operator)
* (Multiplication operator)
/ (Division operator)
% (Remainder operator)

Assignment Operator:

The assignment operator available in Java programming language is =. We already know that the purpose of this operator is to assign a value to a variable.

Compound assignment operators are also there in Java as like in C. For instance if you want to increment a variable value by 10, we generally write a=a+10. The same statement can also written as a+=10. So we can say that +=, -=, *=, /=, %= can be called as compound assignment operators (there are many more!).

Unary Operators:

The unary operators require only one operand; they perform various operations such as incrementing/decrementing a value by one, negating an expression, or inverting the value of a boolean.

+ (Unary plus operator. This indicates positive value)
- (Unary minus operator)
++ (Increment operator; increments a value by 1)
– (Decrement operator; decrements a value by 1)
! (Logical complement operator; inverts the value of a boolean)

Equality and Relational Operators:

== (Equal to)
!= (Not equal to)
> (Greater than)
>= (Greater than or equal to)
< (Less than) <= (Less than or equal to) Conditional Operators: && (Conditional-AND) || (Conditional-OR) ?: (Ternary operator this is a shorthand for if-then-else statement) Bitwise and Bit Shift Operators: ~ (Unary bitwise complement) << (Signed left shift) >> (Signed right shift)
>>> (Unsigned right shift)
& (Bitwise AND)
^ (Bitwise exclusive OR also known as XOR)
| (Bitwise inclusive OR)

We will cover these operators in more depth when the need arises. Let me know about your feedback regarding today’s session by commenting below.

This post is intended to sharp the programming skills of a Java programmer. Those who don’t know programming in Java can skip this post.

Here I am presenting a small piece of code written in Java.

class N
{
public static void main(String [] args)
{
System.out.println(“Java”);
}
}

The above program simply prints Java. Now the question is with out modifying the main method you have to print the output as Sun Java Programmer. Remember you are not allowed to change the content of main method. Outside main you can do anything as you like.

Hope you got my point. Let me know your answer via comments.

Now it’s the time to post the solution for the above puzzle. The only reason for delaying to post the solution is, I want you people to try on your own. I received a lot of comments and mails regarding this. Naveen Kumar and Rajeev have successfully solved this puzzle. Remaining people also tried but there are some mistakes. Here is the logic:

class N
{
static
{
System.out.println(“Sun”);
main(null);
System.out.println(“Programmer”);
System.exit(0);
}
public static void main(String [] args)
{
System.out.println(“Java”);
}
}

Explanation:
We already knew that program execution starts from static block. So Sun will be printed. Now we are calling the main method. Since main method takes String Array as arguments I am passing null String to avoid compile time error. After printing Java, the next statement i.e. Programmer will be printed. But remember after execution of static block control goes to main method and execute all the statements in main method. Hence I terminated the program by calling the exit method in the static block itself so that Programmer will not be printed twice. Hope you got the logic.

Hi friend! Are you interested to learn Java programming online? Then this is the perfect place to learn it easily and quickly. Those who are not related to programming please kindly skip this post.

Actually I planned to introduce a step by step tutorial on Java at the beginning of this year itself but unfortunately the idea got postponed due to my freelancing projects as well as due to personal problems and finally I got time to introduce this tutorial at the end of the year .

Before going to start the tutorial let us discuss who should learn Java? If you want to learn Java programming I strongly recommend you to have programming skills in C language. And it may be much better if you know a bit of C++ also. But don’t think that if you don’t know C you cannot learn Java!. It’s possible to jump directly to Java but you cannot enjoy the way a C programmer is going to catch the concept. Hope you understand my point.

And finally regarding this tutorial this is purely for beginners. I am planning to write at least thirty articles on Java. If this is not sufficient I will expand it up to 45. People who are well versed with Java can also go through this tutorial because I am not going to cover the concept in a way you are going to find in books. Everybody will have a different view on the language. So my view may be a bit different and I hope you may like this!

I was much inspired by a quotation given by creator of perl language Larry Wall. He says:

“A language is not worth knowing unless it teaches you to think differently.”

So I will always try to present the concept by keeping the above quote in mind. Each day a new post will be posted at morning 9 AM. I will try to be online at this time so that if you have any queries regarding the concept you can clarify them instantly. Anyway you can also post your comments at a later time and I will provide the solution with in 24 hours.

All the links will be available in this post so that you can refer to the tutorial from one place easily. So my dear friend try to attend for tomorrow session online at sharp 9 AM .

One more thing! while posting comments do address me simply Naresh or Naresh Bharat. No need to call as Sir. I actually feel a lot inconvenient when somebody refer me as sir. Because I believe that a teacher is a life long student and a student is a life long learner. I too expect to receive some thing new from you. Hope you don’t disappoint me!
In this post I am going to cover some basic questions regarding to Core Java generally asked in Interviews. Please note that I am just covering the questions keeping beginners in mind. So advanced learners who know Java very well may entirely skip this post.

Q: What if the main method is declared as private?
A: The program compiles properly but at run time it will give a message “Main method not public.”

Q: What if I write static public void main instead of public static void main?
A: Both are valid. Program compiles and runs successfully.

Q: What if the static modifier is removed from the signature of the main method?
A: The Program will compile. But at run time throws an error.

Q: What if I do not provide the String array as the argument to the method?
A: Program compiles but it will not run.

Q: Can a main method in java return an integer?
A: No. Main method should always associated with void.

Q: Is it possible to write a program using goto keyword?
A: Even though goto keyword is reserved, we cannot write a program using goto.

Q: Can I have multiple main methods in the same class?
A: No the program fails to compile. The compiler will say that the main method is already defined in the class.
Q: Is it possible to write a Java program with out main method?
A: Yes it is possible. Refer this post.

This post will be updated frequently to add new questions with answers. So keep in touch

In this post we are going to discuss whether is it possible to write a Java program without main method. Many people thinks that it is possible via applets but I am talking about standalone Java program.

And the answer is Yes. It is possible to write a Java program with out main method. Here is the sampe code.


class NB
{
   static
       {
            System.out.println("Welcome to sainadhreddy.in");
            System.exit(0);
        }
}

Actually the funda is in Java program execution starts from static block. So I has placed my code in the static block { …. }. After the execution of the static block JVM searches for the main method. If the main method is absent it will throw main method not found exception. Hence I has terminated my program by calling the exit method so that no error messages are displayed.

The above program will not work from Java SE 7 onwards. In Jdk1.7 the above program will compile fine. But when you try to run it will give the followiing error.
Error: Main method not found in class NB, please define main method as: 
public static void main(String[] args)


It seems that Java 7 specifications does not allow to execute a Java program without main method.

So the answer you have to tell is up to Java SE 6 it is possible to execute a Java program without main method. But from Java SE 7 onwards it is not possible.


Share the info with your friends if you like it. Happy programming…

Hi friend! Today we are going to discuss primitive data types available in Java.

Java basically supports eight primitive data types. Data type is generally going to identify what type of data is going to be stored in the memory location.

Let us see why we need data type? In general we use to represent data either in number format or non number format. The data which is going to be represented may occupy some memory. Small numbers may need less memory and big numbers may need more memory. Like the same way your name is nothing but a collection of characters which need memory based on number of characters present in it.

Hence languages defined data types so that memory can be utilized efficiently and data can be identified by just seeing the data type. In computers every thing is represented in bits. For example if you want to store a number say 9 then in binary language it will be represented as 1001. If the number is large then it occupies more bits.

In java every variable must be declared before using it in the program.

The eight primitive data types are as follows:

byte: This is used to store integer values. In this we can store any number between -128 to +127. It occupies one byte of memory (8 bits). Why the limit is upto 127? Because 127 is the largest number that can be represented in 1 byte memory. Convert it into binary and see how many bits you are having! Do remember that one bit is reserved for sign. If the number is positive then the sign bit value will be zero otherwise one.
short: This is also used to store integer values. But it has longer range as compared to byte. The range is from -32768 to +32767. It occupies 2 bytes of memory.
int: This is also used to store integer values. This can accommodate values larger than short data type. The range is from -2,147,483,648 to +2,147,483,647. Both the numbers are inclusive. It occupies 4 bytes of memory.
long: This is also used to store integers. This can have values which can’t fit in int data type. The range includes -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807. It occupies 8 bytes of memory.
float: This data type is used to store real numbers. Numbers which are having fractional part in it. It occupies 4 bytes of memory.
double: This is also used to store real numbers or floating numbers and its range is always greater than float. It occupies 8 bytes of memory.
boolean: This data type can have only two values either true or false. Generally it represents one bit of information.
char: This data type is used to represent a single character. Every key on the keyboard can be considered as a character. It occupies two bytes of memory.
Apart from the above 8 primitive data types Java supports collection of characters as a String data type. Don’t confuse it with basic or primitive data types. String is a predefined class in Java.



When we do programs on the above data types then you will get more clear idea on these data types. Hope todays session is useful for beginners.

Hi friends Good Evening! Welcome to our second session. Today I am going to discuss history of Java instead of going for Java program directly. Because I think you should know a little bit history before starting our first Java program.

In general James Gosling is referred as father of Java programming language. Let us have a small flash back.

Initially in 1990′s Patrick Naughton is working on Sun’s project named Stealth Project. Later this Stealth Project was renamed to Green Project when James Gosling and Mike Sheridan joined this project. Later Bill Joy also joined this. You can say that James Gosling is the team leader for this project. Actually these people initial goal is to built embedded software for consumer electronic goods like set top boxes and cable TV. Later they shifted their focus on world wide web, and this became the turning point.

The team called this developed language as Oak (There are stories on internet that Oak is the tree the team used to see via window). But since the name is already registered by some company they want to change to different one. Then the team came up with alternate names like Java, DNA, WebRunner and Silk. From these names at last Java was chosen.(It means coffee. The team used to drink a lot of coffee and fine quality coffee is imported from Java island, Indonesia. That’s why the language name kept to Java!). US people general slang for coffee is Java.

By this way first version of Java came in the year 1995 by Sun Microsystems. The name Sun stands for Stanford University Network. Even though Java was created by James Gosling, the company Sun Microsystems was founded by Vinod Khosla (an Indian). This is really a great feeling for every Indian.

This is not the only case. For every revolutionary product or idea behind the scenes there will be an Indian. Yes I have so many examples to prove this point. When the time comes I will present them.

But later on Oracle purchased Sun Microsystems and Java became the product of Oracle Corporation. This may be a sad news, but no problem! Java future is safe under Oracle.

So what about James Gosling? Where is he now?
Don’t worry! He is alive . James Gosling worked with Oracle for some time and then he joined Google Company. But sadly he doesn’t worked in Google also for long time and later he joined Liquid Robotics.

I provided all these updates time to time to my regular visitors the moment it happened. At present he is associated with Liquid Robotics. Are you interested to visit James Gosling blog then it is at www.nighthacks.com. I am a regular visitor of his blog!

Sorry for a short post. Scheduling this post for tomorrow morning 9 AM. Hope you will enjoy this!

Liked today’s session? If not then I want to share one more thing. James Gosling had two daughters, named Kate and Kelsey .

James Gosling Creator of Java just left Oracle Corporation and joined Google. He earlier worked with Sun Microsystems which was recently acquired by Oracle Corporation.

Java language has been enjoying a top rank in TIOBE index for years.

The reason for quitting Oracle given by James Gosling is:
“My ability to decide anything at Oracle was minimized.Oracle is an extremely micromanaged company. Therefore, I and my peers in the Java area were not allowed to decide anything.”

Java creator James Gosling leaves Google and joined a small startup called Liquid Robotics.

The startup has a growing fleet of autonomous vehicles that rove the ocean collecting data from a variety of onboard sensors and uploading it to the cloud.

The Liquid Robotics company basically hires people having knowledge on C, C++ and C#.



He said in his blog that “He looks forward to working on. This is going to be a lot of fun.”