Friday, August 21, 2015

Java while loop

Java while loop is used to execute statement(s) until a condition holds true. In this tutorial we will learn looping using Java while loop examples. First of all lets discuss while loop syntax:

while (condition(s)) {
// Body of loop
}

1. If the condition holds true then the body of loop is executed, after execution of loop body condition is tested again and if the condition is true then body of loop is executed again and the process repeats until condition becomes false. Condition is always evaluated to true or false and if it is a constant, For example while (c) { …} where c is a constant then any non zero value of c is considered true and zero is considered false.

2. You can test multiple conditions such as

while ( a > b && c != 0) {
 // Loop body
}

Loop body is executed till value of a is greater than value of b and c is not equal to zero.

3. Body of loop can contain more than one statement. For multiple statements you need to place them in a block using {} and if body of loop contain only single statement you can optionally use {}. It is recommended to use braces always to make your program easily readable and understandable.
Java while loop example

Following program asks the user to input an integer and prints it until user enter 0 (zero).

import java.util.Scanner;
 
class WhileLoop {
 public static void main(String[] args) {
 int n;
 
 Scanner input = new Scanner(System.in);
 System.out.println("Input an integer"); 
 
 while ((n = input.nextInt()) != 0) {
 System.out.println("You entered " + n);
 System.out.println("Input an integer");
 }
 
 System.out.println("Out of loop");
 }
}

Output of program:


Above program can be written in a more compact way as follows:

// Java while loop user input 
import java.util.Scanner;
 
class WhileLoop {
 public static void main(String[] args) {
 int n;
 
 Scanner input = new Scanner(System.in);
 System.out.println("Input an integer"); 
 
 while ((n = input.nextInt()) != 0) {
 System.out.println("You entered " + n);
 System.out.println("Input an integer");
 }
 }
}

Java while loop break program


Here we write above program but uses break statement. The condition in while loop here is always true so we test the user input and if its is zero then we use break to exit or come out of the loop.

import java.util.Scanner;
 
class BreakWhileLoop {
 public static void main(String[] args) {
 int n;
 
 Scanner input = new Scanner(System.in);
 
 while (true) {
 System.out.println("Input an integer");
 n = input.nextInt();
 
 if (n == 0) {
 break;
 }
 System.out.println("You entered " + n);
 }
 }
}

Java while loop break continue program


import java.util.Scanner;
 
class BreakContinueWhileLoop {
 public static void main(String[] args) {
 int n;
 
 Scanner input = new Scanner(System.in);
 
 while (true) {
 System.out.println("Input an integer");
 n = input.nextInt();
 
 if (n != 0) {
 System.out.println("You entered " + n);
 continue;
 }
 else {
 break;
 }
 }
 }
}

Whatever you can do with while loop can be done with for and do while loop.

Java for loop


Java for loop used to repeat execution of statement(s) until a certain condition holds true. for is a keyword in Java programming language.

Java for loop syntax


for (/* Initialization of variables */ ; /*Conditions to test*/ ; /* Increment(s) or decrement(s) of variables */) {
 // Statements to execute i.e. Body of for loop
}

You can initialize multiple variables, test many conditions and perform increments or decrements on many variables according to requirement. Please note that all three components of for loop are optional. For example following for loop prints "Java programmer" indefinitely.

// Infinite for loop
for (;;) {
 System.out.println("Java programmer");
}

You can terminate an infinite loop by pressing Ctrl+C.

Simple for loop example in Java


Example program below uses for loop to print first 10 natural numbers i.e. from 1 to 10.

//Java for loop program
class ForLoop {
 public static void main(String[] args) {
 int c;
 
 for (c = 1; c <= 10; c++) {
 System.out.println(c);
 }
 }
}

Output of program:


Java for loop example to print stars in console


Following star pattern is printed
*
**
***
****
*****

class Stars {
 public static void main(String[] args) {
 int row, numberOfStars;
 
 for (row = 1; row <= 10; row++) {
 for(numberOfStars = 1; numberOfStars <= row; numberOfStars++) {
 System.out.print("*");
 }
 System.out.println(); // Go to next line
 }
 }
}

Above program uses nested for loops (for loop inside a for loop) to print stars. You can also use spaces to create another pattern, It is left for you as an exercise.

Output of program:

Thursday, August 20, 2015

Java if else Program

Java if else program uses if else to execute statement(s) when a condition is fulfilled. Below is a simple program which explains the usage of if else in java programming language.

Java programming if else statement

// If else in Java code
import java.util.Scanner;
 
class IfElse {
 public static void main(String[] args) {
 int marksObtained, passingMarks;
 
 passingMarks = 40;
 
 Scanner input = new Scanner(System.in);
 
 System.out.println("Input marks scored by you");
 
 marksObtained = input.nextInt();
 
 if (marksObtained >= passingMarks) {
 System.out.println("You passed the exam.");
 }
 else {
 System.out.println("Unfortunately you failed to pass the exam.");
 }
 }
}

Output:



Above program ask the user to enter marks obtained in exam and the input marks are compared against minimum passing marks. Appropriate message is printed on screen based on whether user passed the exam or not. In the above code both if and else block contain only one statement but we can execute as many statements as required.

Nested If Else statements


You can use nested if else which means that you can use if else statements in any if or else block.

import java.util.Scanner;
 
class NestedIfElse {
 public static void main(String[] args) {
 int marksObtained, passingMarks;
 char grade;
 
 passingMarks = 40;
 
 Scanner input = new Scanner(System.in);
 
 System.out.println("Input marks scored by you");
 
 marksObtained = input.nextInt();
 
 if (marksObtained >= passingMarks) {
 
 if (marksObtained > 90) 
 grade = 'A';
 else if (marksObtained > 75)
 grade = 'B';
 else if (marksObtained > 60)
 grade = 'C';
 else
 grade = 'D'; 
 
 System.out.println("You passed the exam and your grade is " + grade);
 }
 else {
 grade = 'F'; 
 System.out.println("You failed and your grade is " + grade);
 }
 }
}

Output:

Java programming examples


Example 1: Display message on computer screen.

class First {
 public static void main(String[] arguments) {
 System.out.println("Let's do something using Java technology.");
 }
}

This is similar to hello world java program. Go to cmd to compile and then interpret the program using javac the inbuilt java compiler and then it will interpret it using java and then Class file name. Here you can also use First.class instead of only First in the second line just after java.

Output:




Example 2: Print integers

class Integers {
 public static void main(String[] arguments) {
 int c; //declaring a variable
 
 /* Using for loop to repeat instruction execution */
 
 for (c = 1; c <= 10; c++) {
 System.out.println(c);
 }
 }
}

Output:




If else control instructions:

class Condition {
 public static void main(String[] args) {
 boolean learning = true;
 
 if (learning) {
 System.out.println("Java programmer");
 }
 else {
 System.out.println("What are you doing here?");
 }
 }
}

Output:




Command line arguments:

class Arguments {
 public static void main(String[] args) {
 for (String t: args) {
 System.out.println(t);
 }
 }
}

Output:

Difference Between Java and C#

One of the most important aspects of C-derived languages is object orientation. Objects and classes allow programs to specify methods and variables in one portion of code and use them again wherever necessary. While the basic structures of class construction remain consistent between C# and Java, some subtle differences my cause problems for developers unaccustomed to the idiosyncrasies between the two languages.

#1: Instance-level inner classes

C#: Work-around support Instance-level inner classes

Java: Support for Instance-level inner classes

An inner class (also called a “nested class”) is declared entirely inside another class or interface. Although both languages support inner classes at the Class level, only Java supports these inner classes at the instance level without the need to pass around the outer object instance. Java handles the instance-level inner class with an “outer this pointer”.

#2: Partial Classes

C#: Supports partial classes

Java: No support for partial classes

A “partial class” is a class whose methods and variables are parceled out into multiple files. When the files are compiled, the class reassembles itself into the full class definition. While the C# 2.0 compiler (and other OOP compilers) allows for class files to merge at compile time, the Java compiler does not. In Java, each class must be in its own specific source code file.

#3: Anonymous Classes

C#: Supports statement-level anonymous classes

Java: Supports implicit anonymous classes

An anonymous class is just that: a class without a name. Developers often define anonymous classes within a method to build simple delegate callback objects, such as those used in listener methods. Java treats anonymous classes as implicit, but C# code must defined the anonymous class at the statement level.

#4: Properties

C#: Supports properties

Java: Does not support properties

A property uses the tools of a method while holding a value like a variable:

// Declare a Name property of type string:

public string Name
{
 get
 {
 return myName;
 }
 set
 {
 myName = value;
 }
}

Although other Java-related languages and toolsets (e.g. JavaBeans and JavaScript) support similar ways of defining a property, Java does not.

#5: Events

C#: Supports events

Java: Work-around support for events

An event is a way that a class can notify its clients that an action has occurred that affects some method or variable within the object. Although Java does not support the “event” keyword for this specific purpose, Java developers can create a class that has much of the same behavior as an event.

Honorable Mentions

Operator Overloading

C#: Supports

Java: Does not support

According to the Java FAQ, Java does not support operator overloading “because C++ has proven by example that operator overloading makes code almost impossible to maintain”.


Indexers

C#: Supports

Java: Does not support

Indexers allow class instances to be indexed and counted in ways similar to arrays for variables. Class instances in Java can still be indexed, but the “get” and “set” methods must be specified as variables.


Example: http://www.javacamp.org/javavscsharp/indexer.html


Conversions

C#: Supports

Java: Does not support

C# allows both implicit and explicit conversions from one data type to another. Java requires that the user specifically state the conversion method.


Other Differences between Java and C#


  • C# and java both were derived from C++, and therefore they have similar roots, both are widely used for web programming. We discuss the difference between C# and java these are as follows: 
  • C# has more primitive datatypes 
  • Java uses static final to declare a class constant while C# uses const. 
  • Java does not provide for operator overloading. 
  • C# supports the struct type and java does not. 
  • Unlike java, all C# datatypes are object. 
  • C# provides static constructors for initialization. 
  • In java, parameters are always passed by value, c# allows parameters to be passed by reference by Ref keyword. 
  • C# includes native support for properties, java does not. 
  • Java does not directly support enumerations. 
  • In java, the switch statement can have only integer expression, in C# supports integer and string both.