Sunday, August 23, 2015

Java program to find odd or even

This java program finds if a number is odd or even. If the number is divisible by 2 then it will be even, otherwise it is odd. We use modulus operator to find remainder in our program.

Java programming source code


import java.util.Scanner;
 
class OddOrEven
{
 public static void main(String args[])
 {
 int x;
 System.out.println("Enter an integer to check if it is odd or even ");
 Scanner in = new Scanner(System.in);
 x = in.nextInt();
 
 if ( x % 2 == 0 )
 System.out.println("You entered an even number.");
 else
 System.out.println("You entered an odd number.");
 }
}

Output of program:


Another method to check odd or even

import java.util.Scanner;
 
class EvenOdd
{
 public static void main(String args[])
 {
 int c;
 System.out.println("Input an integer");
 Scanner in = new Scanner(System.in);
 c = in.nextInt();
 
 if ( (c/2)*2 == c )
 System.out.println("Even");
 else
 System.out.println("Odd");
 }
}

There are other methods for checking odd/even one such method is using bitwise operator.

import java.util.Scanner;
public class EvenOrOdd { 
public static void main(String args[]) { 
Scanner obj = new Scanner(System.in);
int no;
System.out.println("Enter any number to check if it is Even or Odd number:");
no = obj.nextInt();
isOddOrEven(no); 
}
public static void isOddOrEven(int number){ 
if((number & 1) == 0){ 
System.out.println("Using bitwise operator: " + number + " is Even number"); 
}
else{ 
System.out.println("Using bitwise operator: " + number + " is Odd number"); 
} 
} 
}

Output of program:

Java program to add two numbers

Given below is the code of java program that adds two numbers which are entered by the user.

Java programming source code


import java.util.Scanner;
 
class AddNumbers
{
 public static void main(String args[])
 {
 int x, y, z;
 System.out.println("Enter two integers to calculate their sum ");
 Scanner in = new Scanner(System.in);
 x = in.nextInt();
 y = in.nextInt();
 z = x + y;
 System.out.println("Sum of entered integers = "+z);
 }
}

Output of program:


Above code can add only numbers in range of integers(4 bytes), if you wish to add very large numbers then you can use BigInteger class. Code to add very large numbers:

import java.util.Scanner;
import java.math.BigInteger;
 
class AddingLargeNumbers {
 public static void main(String[] args) {
 String number1, number2;
 Scanner in = new Scanner(System.in);
 
 System.out.println("Enter first large number");
 number1 = in.nextLine();
 
 System.out.println("Enter second large number");
 number2 = in.nextLine();
 
 BigInteger first = new BigInteger(number1);
 BigInteger second = new BigInteger(number2);
 BigInteger sum;
 
 sum = first.add(second);
 
 System.out.println("Result of addition = " + sum);
 }
}

In our code we create two objects of BigInteger class in java.math package. Input should be digit strings otherwise an exception will be raised, also you cannot simply use '+' operator to add objects of BigInteger class, you have to use add method for addition of two objects.

Output of program:
Enter first large number
11111111111111
Enter second large number
 99999999999999
Result of addition = 111111111111110

Saturday, August 22, 2015

How to get input from user in java

This program tells you how to get input from user in a java program. We are using Scanner class to get input from user. This program firstly asks the user to enter a string and then the string is printed, then an integer and entered integer is also printed and finally a float and it is also printed on the screen. Scanner class is present in java.util package so we import this package in our program. We first create an object of Scanner class and then we use the methods of Scanner class. Consider the statement:

Scanner a = new Scanner(System.in);

Here Scanner is the class name, a is the name of object, new keyword is used to allocate the memory and System.in is the input stream. Following methods of Scanner class are used in the program below:-
1) nextInt to input an integer
2) nextFloat to input a float
3) nextLine to input a string
Java programming source code

import java.util.Scanner;
 
class GetInputFromUser
{
 public static void main(String args[])
 {
 int a;
 float b;
 String s;
 
 Scanner in = new Scanner(System.in);
 
 System.out.println("Enter a string");
 s = in.nextLine();
 System.out.println("You entered string "+s);
 
 System.out.println("Enter an integer");
 a = in.nextInt();
 System.out.println("You entered integer "+a);
 
 System.out.println("Enter a float");
 b = in.nextFloat();
 System.out.println("You entered float "+b); 
 }
}

Output of program:


There are other classes which can be used for getting input from user and you can also take input from other devices.

Java program to print multiplication table


This java program prints multiplication table of a number entered by the user using a for loop. You can modify it for while or do while loop for practice.

Java programming source code


import java.util.Scanner;
 
class MultiplicationTable
{
 public static void main(String args[])
 {
 int n, c;
 System.out.println("Enter an integer to print it's multiplication table");
 Scanner in = new Scanner(System.in);
 n = in.nextInt();
 System.out.println("Multiplication table of "+n+" is :-");
 
 for ( c = 1 ; c <= 10 ; c++ )
 System.out.println(n+"*"+c+" = "+(n*c));
 }
}

Output of program:



Using nested loops we can print tables of number between a given range say a to b, For example if the input numbers are 3 and 6 then tables of 3, 4, 5 and 6 will be printed. Code:

import java.util.Scanner;
 
class Tables
{
 public static void main(String args[])
 {
 int a, b, c, d;
 
 System.out.println("Enter range of numbers to print their multiplication table");
 Scanner in = new Scanner(System.in);
 
 a = in.nextInt();
 b = in.nextInt();
 
 for (c = a; c <= b; c++) {
 System.out.println("Multiplication table of "+c);
 
 for (d = 1; d <= 10; d++) {
 System.out.println(c+"*"+d+" = "+(c*d));
 }
 }
 }
}

Friday, August 21, 2015

Java program to print alphabets


This program print alphabets on screen i.e a, b, c, ..., z. Here we print alphabets in lower case.

Java source code


class Alphabets
{
 public static void main(String args[])
 {
 char ch;
 
 for( ch = 'a' ; ch <= 'z' ; ch++ )
 System.out.println(ch);
 }
}

You can easily modify the above java program to print alphabets in upper case.

Output of program:


Printing alphabets using while loop (only body of main method is shown):
char c = 'a';
 
while (c <= 'z') {
 System.out.println(c);
 c++;
}

Using do while loop:
char c = 'A';
 
do {
 System.out.println(c);
 c++;
} while (c <= 'Z');

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.

Wednesday, August 19, 2015

Comparing C++ and Java

Many developers already have experience with an object-oriented programming language like C++. As you make the transition to Java, you will encounter many differences, despite some strong similarities.

As a C++ programmer, you already have the basic idea of object-oriented programming, and the syntax of Java no doubt looks familiar to you. This makes sense since Java was derived from C++. However, there are a surprising number of differences between C++ and Java.

These differences are intended to be significant improvements, and if you understand the differences you'll see why Java is such a beneficial programming language. This article takes you through the important features that distinguish Java from C++.
  1. The biggest potential stumbling block is speed: interpreted Java runs in the range of 20 times slower than C. Nothing prevents the Java language from being compiled and there are just-in-time compilers appearing at this writing that offer significant speed-ups. It is not inconceivable that full native compilers will appear for the more popular platforms, but without those there are classes of problems that will be insoluble with Java because of the speed issue.
  2. Java has both kinds of comments like C++ does.
  3. Everything must be in a class. There are no global functions or global data. If you want the equivalent of globals, make static methods and static data within a class. There are no structs or enumerations or unions, only classes.
  4. All method definitions are defined in the body of the class. Thus, in C++ it would look like all the functions are inlined, but they're not (inlines are noted later).
  5. Class definitions are roughly the same form in Java as in C++, but there's no closing semicolon. There are no class declarations of the form class foo, only class definitions.
    class aType {
        void aMethod( ) { /* method body */ }
    }
    
  6. There's no scope resolution operator :: in Java. Java uses the dot for everything, but can get away with it since you can define elements only within a class. Even the method definitions must always occur within a class, so there is no need for scope resolution there either. One place where you'll notice the difference is in the calling of staticmethods: you say ClassName.methodName( );. In addition,package names are established using the dot, and to perform a kind of C++ #include you use the import keyword. For example: import java.awt.*;. (#include does not directly map to import, but it has a similar feel to it).
  7. Java, like C++, has primitive types for efficient access. In Java, these are booleancharbyteshortintlongfloat, and double. All the primitive types have specified sizes that are machine independent for portability. (This must have some impact on performance, varying with the machine.) Type-checking and type requirements are much tighter in Java. For example:

    1. Conditional expressions can be only boolean, not integral.

    2. The result of an expression like X + Y must be used; you can't just say "X + Y" for the side effect.
  8. The char type uses the international 16-bit Unicode character set, so it can automatically represent most national characters.
  9. Static quoted strings are automatically converted into String objects. There is no independent static character array string like there is in C and C++.
  10. Java adds the triple right shift >>> to act as a "logical" right shift by inserting zeroes at the top end; the >> inserts the sign bit as it shifts (an "arithmetic" shift).
  11. Although they look similar, arrays have a very different structure and behavior in Java than they do in C++. There's a read-only length member that tells you how big the array is, and run-time checking throws an exception if you go out of bounds. All arrays are created on the heap, and you can assign one array to another (the array handle is simply copied). The array identifier is a first-class object, with all of the methods commonly available to all other objects.
  12. All objects of non-primitive types can be created only via new. There's no equivalent to creating non-primitive objects "on the stack" as in C++. All primitive types can be created only on the stack, without new. There are wrapper classes for all primitive classes so that you can create equivalent heap-based objects via new. (Arrays of primitives are a special case: they can be allocated via aggregate initialization as in C++, or by using new.)
  13. No forward declarations are necessary in Java. If you want to use a class or a method before it is defined, you simply use it, the compiler ensures that the appropriate definition exists. Thus you don't have any of the forward referencing issues that you do in C++.
  14. Java has no pre-processor. If you want to use classes in another library, you say import and the name of the library. There are no pre-processor like macros.
  15. Java uses packages in place of namespaces. The name issue is taken care of by putting everything into a class and by using a facility called "packages" that performs the equivalent namespace breakup for class names. Packages also collect library components under a single library name. You simply import a package and the compiler takes care of the rest.
  16. Object handles defined as class members are automatically initialized to null. Initialization of primitive class data members is guaranteed in Java; if you don't explicitly initialize them they get a default value (a zero or equivalent). You can initialize them explicitly, either when you define them in the class or in the constructor. The syntax makes more sense than that for C++, and is consistent for static and non-static members alike. You don't need to externally define storage for static members like you do in C++.
  17. There are no Java pointers in the sense of C and C++. When you create an object with new, you get back a reference. For example:
    String s = new String("howdy");

    However, unlike C++ references that must be initialized when created and cannot be rebound to a different location, Java references don't have to be bound at the point of creation. They can also be rebound at will, which eliminates part of the need for pointers. The other reason for pointers in C and C++ is to be able to point at any place in memory whatsoever (which makes them unsafe, which is why Java doesn't support them). Pointers are often seen as an efficient way to move through an array of primitive variables; Java arrays allow you to do that in a safer fashion. The ultimate solution for pointer problems is native methods (discussed in Appendix A). Passing pointers to methods isn't a problem since there are no global functions, only classes, and you can pass references to objects.
  18. The Java language promoters initially said "No pointers!", but when many programmers questioned how you can work without pointers, the promoters began saying "Restricted pointers." You can make up your mind whether it's "really" a pointer or not. In any event, there's no pointer arithmetic.
  19. Java has constructors that are similar to constructors in C++. You get a default constructor if you don't define one, and if you define a non-default constructor, there's no automatic default constructor defined for you, just like in C++. There are no copy constructors, since all arguments are passed by reference.
  20. There are no destructors in Java. There is no "scope" of a variable to indicate when the object's lifetime is ended, the lifetime of an object is determined instead by the garbage collector. There is a finalize( ) method that's a member of each class, something like a C++ destructor, but finalize( ) is called by the garbage collector and is supposed to be responsible only for releasing "resources" (such as open files, sockets, ports, URLs, etc). If you need something done at a specific point, you must create a special method and call it, not rely upon finalize( ). Put another way, all objects in C++ will be (or rather, should be) destroyed, but not all objects in Java are garbage collected. Because Java doesn't support destructors, you must be careful to create a cleanup method if it's necessary and to explicitly call all the cleanup methods for the base class and member objects in your class.
  21. Java has method overloading that works virtually identically to C++ function overloading.
  22. Java does not support default arguments.
  23. There's no goto in Java. The one unconditional jump mechanism is the break label or continue label, which is used to jump out of the middle of multiply-nested loops.
  24. Java uses a singly-rooted hierarchy, so all objects are ultimately inherited from the root class Object. In C++, you can start a new inheritance tree anywhere, so you end up with a forest of trees. In Java you get a single ultimate hierarchy. This can seem restrictive, but it gives a great deal of power since you know that every object is guaranteed to have at least the Object interface. C++ appears to be the only OO language that does not impose a singly rooted hierarchy.
  25. Java has no templates or other implementation of parameterized types. There is a set of collections: Vector,Stack, and Hashtable that hold Object references, and through which you can satisfy your collection needs, but these collections are not designed for efficiency like the C++ Standard Template Library (STL). The new collections in Java 1.2 are more complete, but still don't have the same kind of efficiency as template implementations would allow.
  26. Garbage collection means memory leaks are much harder to cause in Java, but not impossible. (If you make native method calls that allocate storage, these are typically not tracked by the garbage collector.) However, many memory leaks and resouce leaks can be tracked to a badly written finalize( ) or to not releasing a resource at the end of the block where it is allocated (a place where a destructor would certainly come in handy). The garbage collector is a huge improvement over C++, and makes a lot of programming problems simply vanish. It might make Java unsuitable for solving a small subset of problems that cannot tolerate a garbage collector, but the advantage of a garbage collector seems to greatly outweigh this potential drawback.
  27. Java has built-in multi-threading support. There's a Thread class that you inherit to create a new thread (you override the run( ) method). Mutual exclusion occurs at the level of objects using the synchronized keyword as a type qualifier for methods. Only one thread may use a synchronized method of a particular object at any one time. Put another way, when a synchronized method is entered, it first "locks" the object against any other synchronized method using that object and "unlocks" the object only upon exiting the method. There are no explicit locks; they happen automatically. You're still responsible for implementing more sophisticated synchronization between threads by creating your own "monitor" class. Recursive synchronized methods work correctly. Time slicing is not guaranteed between equal priority threads.
  28. Instead of controlling blocks of declarations like C++ does, the access specifiers (publicprivate, and protected) are placed on each definition for each member of a class. Without an explicit access specifier, an element defaults to "friendly," which means that it is accessible to other elements in the same package (equivalent to them all being C++ friends) but inaccessible outside the package. The class, and each method within the class, has an access specifier to determine whether it's visible outside the file. Sometimes the private keyword is used less in Java because "friendly" access is often more useful than excluding access from other classes in the same package. (However, with multi-threading the proper use ofprivate is essential.) The Java protected keyword means "accessible to inheritors and to others in this package." There is no equivalent to the C++ protected keyword that means "accessible to inheritors only" (private protected used to do this, but the use of that keyword pair was removed).
  29. Nested classes. In C++, nesting a class is an aid to name hiding and code organization (but C++ namespaces eliminate the need for name hiding). Java packaging provides the equivalence of namespaces, so that isn't an issue. Java 1.1 has inner classes that look just like nested classes. However, an object of an inner class secretly keeps a handle to the object of the outer class that was involved in the creation of the inner class object. This means that the inner class object may access members of the outer class object without qualification, as if those members belonged directly to the inner class object. This provides a much more elegant solution to the problem of callbacks, solved with pointers to members in C++.
  30. Because of inner classes described in the previous point, there are no pointers to members in Java.
  31. No inline methods. The Java compiler might decide on its own to inline a method, but you don't have much control over this. You can suggest inlining in Java by using the final keyword for a method. However, inline functions are only suggestions to the C++ compiler as well.
  32. Inheritance in Java has the same effect as in C++, but the syntax is different. Java uses the extends keyword to indicate inheritance from a base class and the super keyword to specify methods to be called in the base class that have the same name as the method you're in. (However, the super keyword in Java allows you to access methods only in the parent class, one level up in the hierarchy.) Base-class scoping in C++ allows you to access methods that are deeper in the hierarchy). The base-class constructor is also called using the super keyword. As mentioned before, all classes are ultimately automatically inherited from Object. There's no explicit constructor initialization list like in C++, but the compiler forces you to perform all base-class initialization at the beginning of the constructor body and it won't let you perform these later in the body. Member initialization is guaranteed through a combination of automatic initialization and exceptions for uninitialized object handles.
    public class Foo extends Bar
    {
       public Foo(String msg) {
          super(msg); // Calls base constructor
       }
       
       public baz(int i) { // Override
          super.baz(i); // Calls base method
       }
    }
    

  33. Inheritance in Java doesn't change the protection level of the members in the base class. You cannot specify public,private, or protected inheritance in Java, as you can in C++. Also, overridden methods in a derived class cannot reduce the access of the method in the base class. For example, if a method is public in the base class and you override it, your overridden method must also be public (the compiler checks for this).
  34. Java provides the interface keyword, which creates the equivalent of an abstract base class filled with abstract methods and with no data members. This makes a clear distinction between something designed to be just an interface and an extension of existing functionality via the extends keyword. It's worth noting that the abstract keyword produces a similar effect in that you can't create an object of that class. An abstract class may contain abstract methods (although it isn't required to contain any), but it is also able to contain implementations, so it is restricted to single inheritance. Together with interfaces, this scheme prevents the need for some mechanism like virtual base classes in C++.

    To create a version of the interface that can be instantiated, use the implements keyword, whose syntax looks like inheritance:
    public interface Face {
       public void smile();
    }
    
    public class Baz extends Bar implements Face {
       public void smile( ) {
          System.out.println("a warm smile");
       }
    }
    
  35. There's no virtual keyword in Java because all non-static methods always use dynamic binding. In Java, the programmer doesn't have to decide whether to use dynamic binding. The reason virtual exists in C++ is so you can leave it off for a slight increase in efficiency when you're tuning for performance (or, put another way, "If you don't use it, you don't pay for it"), which often results in confusion and unpleasant surprises. The final keyword provides some latitude for efficiency tuning, it tells the compiler that this method cannot be overridden, and thus that it may be statically bound (and made inline, thus using the equivalent of a C++ non-virtual call). These optimizations are up to the compiler.
  36. Java doesn't provide multiple inheritance (MI), at least not in the same sense that C++ does. Like protected, MI seems like a good idea but you know you need it only when you are face to face with a certain design problem. Since Java uses a singly-rooted hierarchy, you'll probably run into fewer situations in which MI is necessary. The interface keyword takes care of combining multiple interfaces.
  37. Run-time type identification functionality is quite similar to that in C++. To get information about handle X, you can say, for example:
    X.getClass().getName();
    To perform a type-safe downcast you say:
    derived d = (derived)base;
    just like an old-style C cast. The compiler automatically invokes the dynamic casting mechanism without requiring extra syntax. Although this doesn't have the benefit of easy location of casts as in C++ "new casts," Java checks usage and throws exceptions so it won't allow bad casts like C++ does.
  38. Exception handling in Java is different because there are no destructors. A finally clause can be added to force execution of statements that perform necessary cleanup. All exceptions in Java are inherited from the base class Throwable, so you're guaranteed a common interface.
                
    public void f(Obj b) throws IOException {
       myresource mr = b.createResource();
       try {
          mr.UseResource();
    
       } catch (MyException e) {
          // handle my exception
       } catch (Throwable e) {
          // handle all other exceptions
       } finally {
          mr.dispose(); // special cleanup
       }
    }
  39. Exception specifications in Java are vastly superior to those in C++. Instead of the C++ approach of calling a function at run-time when the wrong exception is thrown, Java exception specifications are checked and enforced at compile-time. In addition, overridden methods must conform to the exception specification of the base-class version of that method: they can throw the specified exceptions or exceptions derived from those. This provides much more robust exception-handling code.
  40. Java has method overloading, but no operator overloading. The String class does use the + and += operators to concatenate strings and String expressions use automatic type conversion, but that's a special built-in case.
  41. The const issues in C++ are avoided in Java by convention. You pass only handles to objects and local copies are never made for you automatically. If you want the equivalent of C++'s pass-by-value, you call clone( ) to produce a local copy of the argument. There's no copy-constructor that's automatically called.

  42. To create a compile-time constant value, you say, for example:

    static final int SIZE = 255;
    static final int BSIZE = 8 * SIZE;
  43. Because of security issues, programming an "application" is quite different from programming an "applet." A significant issue is that an applet won't let you write to disk, because that would allow a program downloaded from an unknown machine to trash your disk. This changes somewhat with Java 1.1 digital signing, which allows you to unequivocally know everyone that wrote all the programs that have special access to your system (one of which might have trashed your disk; you still have to figure out which one and what to do about it.). Java 1.2 also promises more power for applets
  44. Since Java can be too restrictive in some cases, you could be prevented from doing important tasks such as directly accessing hardware. Java solves this with native methods that allow you to call a function written in another language (currently only C and C++ are supported). Thus, you can always solve a platform-specific problem (in a relatively non-portable fashion, but then that code is isolated). Applets cannot call native methods, only applications.
  45. Java has built-in support for comment documentation, so the source code file can also contain its own documentation, which is stripped out and reformatted into HTML via a separate program. This is a boon for documentation maintenance and use.
  46. Java contains standard libraries for solving specific tasks. C++ relies on non-standard third-party libraries. These tasks include (or will soon include):
    • Networking
    • Database Connection (via JDBC)
    • Multi-threading
    • Distributed Objects (via RMI and CORBA)
    • Compression
    • Commerce
    The availability and standard nature of these libraries allow for more rapid application development.
  47. Java 1.1 includes the Java Beans standard, which is a way to create components that can be used in visual programming environments. This promotes visual components that can be used under all vendor's development environments. Since you aren't tied to a particular vendor's design for visual components, this should result in greater selection and availability of components. In addition, the design for Java Beans is simpler for programmers to understand; vendor-specific component frameworks tend to involve a steeper learning curve.
  48. If the access to a Java handle fails, an exception is thrown. This test doesn't have to occur right before the use of a handle; the Java specification just says that the exception must somehow be thrown. Many C++ runtime systems can also throw exceptions for bad pointers.
  49. Generally, Java is more robust, via:
    • Object handles initialized to null (a keyword)
    • Handles are always checked and exceptions are thrown for failures
    • All array accesses are checked for bounds violations
    • Automatic garbage collection prevents memory leaks
    • Clean, relatively fool-proof exception handling
    • Simple language support for multithreading
    • Bytecode verification of network applets

10 Major Differences Between C And JAVA

Here are the major differences between C And JAVA.

1. JAVA is Object-Oriented while C is procedural. Different Paradigms, that is.

Most differences between the features of the two languages arise due to the use of different programming paradigms. C breaks down to functions while JAVA breaks down to Objects. C is more procedure-oriented while JAVA is data-oriented.


2. Java is an Interpreted language while C is a compiled language.

We all know what a compiler does. It takes your code & translates it into something t

C is a low-level language(difficult interpretation for the user, closer significance to the machine-level code) while JAVA is a high-level language(abstracted from the machine-level details, closer significance to the program itself).


4. C uses the top-down {sharp & smooth} approach while JAVA uses the bottom-up {on the rocks} approach.
he machine can understand-that is to say-0’s & 1’s-the machine-level code. That’s exactly what happens with our C code-it gets ‘compiled’. While with JAVA, the code is first transformed to what is called the bytecode. This bytecode is then executed by the JVM(Java Virtual Machine). For the same reason, JAVA code is more portable.


3. C is a low-level language while JAVA is a high-level language.
In C, formulating the program begins by defining the whole and then splitting them into smaller elements. JAVA(and C++ and other OOP languages) follows the bottom-up approach where the smaller elements combine together to form the whole.


5. Pointer go backstage in JAVA while C requires explicit handling of pointers.

When it comes to JAVA, we don’t need the *’s & &’s to deal with pointers & their addressing. More formally, there is no pointer syntax required in JAVA. It does what it needs to do. While in JAVA, we do create references for objects.


6. The Behind-the-scenes Memory Management with JAVA & The User-Based Memory Management in C.

Remember ‘malloc’ & ‘free’? Those are the library calls used in C to allocate & free chunks of memory for specific data(specified using the keyword ‘sizeof’). Hence in C, the memory is managed by the user while JAVA uses a garbage collector that deletes the objects that no longer have any references to them.


7. JAVA supports Method Overloading while C does not support overloading at all.

JAVA supports function or method overloading-that is we can have two or more functions with the same name(with certain varying parameters like return types to allow the machine to differentiate between them). That it to say, we can overload methods with the same name having different method signatures. JAVA(unlike C++), does not support Operator Overloading while C does not allow overloading at all.


8. Unlike C, JAVA does not support pre-processors, & does not really them.

The pre-processor directives like #include & #define, etc are considered one of the most essential elements of C programming. However, there are no pre-processors in JAVA. JAVA uses other alternatives for the preprocessors. For instance, public static final is used instead of the #define pre-processor. Java maps class names to a directory and file structure instead of the #include used to include files in C.


9. The standard Input & Output Functions.

Although this difference might not hold any conceptual(intuitive) significance, but it’s maybe just the tradition. C uses the printf & scanf functions as its standard input & output while JAVA uses the System.out.print & System.in.read functions.


10. Exception Handling in JAVA And the errors & crashes in C.

When an error occurs in a Java program it results in an exception being thrown. It can then be handled using various exception handling techniques. While in C, if there’s an error, there IS an error.


Monday, August 17, 2015

Java Setup with Environment Variables

Download Java here.

After installing the latest version of java, you can manually set the path of the Environment Variables using following instructions.

Setting up the path for windows 2000/XP/7/8/8.1:

Assuming you have installed Java in c:\Program Files\java\jdk directory:

Right-click on 'My Computer' and select 'Properties'.

Click on the 'Environment variables' button under the 'Advanced' tab.

Now, alter the 'Path' variable so that it also contains the path to the Java executable. Example, if the path is currently set to 'C:\WINDOWS\SYSTEM32', then change your path to read 'C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin'.

Setting up the path for windows 95/98/ME:


Assuming you have installed Java in c:\Program Files\java\jdk directory:


Edit the 'C:\autoexec.bat' file and add the following line at the end:
'SET PATH=%PATH%;C:\Program Files\java\jdk\bin'

Setting up the path for Linux, UNIX, Solaris, FreeBSD:


Environment variable PATH should be set to point to where the Java binaries have been installed. Refer to your shell documentation if you have trouble doing this.

Example, if you use bash as your shell, then you would add the following line to the end of your '.bashrc: export PATH=/path/to/java:$PATH'

Popular Java Editors:


To write your Java programs, you will need a text editor. There are even more sophisticated IDEs available in the market. But for now, you can consider one of the following:


Notepad: On Windows machine you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad.


Netbeans:is a Java IDE that is open-source and free which can be downloaded from here.


Eclipse: is also a Java IDE developed by the eclipse open-source community and can be downloaded from here.

Understanding the base elements of Java (Programming Language)

Java is a general-purpose computer programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible. It is intended to let application developers "write once, run anywhere", meaning that compiled Java code can run on all platforms that support Java without the need for recompilation. Java applications are typically compiled to bytecode that can run on any Java virtual machine (JVM) regardless of computer architecture. As of 2015, Java is one of the most popular programming languages in use, particularly for client-server web applications, with a reported 9 million developers. Java was originally developed by James Gosling at Sun Microsystems (which has since been acquired by Oracle Corporation) and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++, but it has fewer low-level facilities than either of them.

The original and reference implementation Java compilers, virtual machines, and class libraries were originally released by Sun under proprietary licences. As of May 2007, in compliance with the specifications of the Java Community Process, Sun relicensed most of its Java technologies under the GNU General Public License. Others have also developed alternative implementations of these Sun technologies, such as the GNU Compiler for Java (bytecode compiler), GNU Classpath (standard libraries), and IcedTea-Web (browser plugin for applets).


Java Programming:-
Hello World

The traditional "Hello, world!" program can be written in Java as:

class HelloWorldApp {
public static void main(String[] args) {
System.out.println("Hello World!"); // Prints the string to the console.
}
}


Source files must be named after the public class they contain, appending the suffix .java, for example, HelloWorldApp.java. It must first be compiled into bytecode, using aJava compiler, producing a file named HelloWorldApp.class. Only then can it be executed, or "launched". The Java source file may only contain one public class, but it can contain multiple classes with other than public access and any number of public inner classes. When the source file contains multiple classes, make one class "public" and name the source file with that public class name.

A class that is not declared public may be stored in any .java file. The compiler will generate a class file for each class defined in the source file. The name of the class file is the name of the class, with .class appended. For class file generation, anonymous classes are treated as if their name were the concatenation of the name of their enclosing class, a $, and an integer.

The keyword public denotes that a method can be called from code in other classes, or that a class may be used by classes outside the class hierarchy. The class hierarchy is related to the name of the directory in which the .java file is located.

The keyword static in front of a method indicates a static method, which is associated only with the class and not with any specific instance of that class. Only static methods can be invoked without a reference to an object. Static methods cannot access any class members that are not also static.

The keyword void indicates that the main method does not return any value to the caller. If a Java program is to exit with an error code, it must call System.exit() explicitly.

The method name "main" is not a keyword in the Java language. It is simply the name of the method the Java launcher calls to pass control to the program. Java classes that run in managed environments such as applets and Enterprise JavaBeans do not use or need a main() method. A Java program may contain multiple classes that have mainmethods, which means that the VM needs to be explicitly told which class to launch from.

The main method must accept an array of String objects. By convention, it is referenced as args although any other legal identifier name can be used. Since Java 5, the main method can also use variable arguments, in the form of public static void main(String... args), allowing the main method to be invoked with an arbitrary number of String arguments. The effect of this alternate declaration is semantically identical (the args parameter is still an array of String objects), but it allows an alternative syntax for creating and passing the array.

The Java launcher launches Java by loading a given class (specified on the command line or as an attribute in a JAR) and starting its public static void main(String[])method. Stand-alone programs must declare this method explicitly. The String[] args parameter is an array of String objects containing any arguments passed to the class. The parameters to main are often passed by means of a command line.

Printing is part of a Java standard library: The System class defines a public static field called out. The out object is an instance of the PrintStream class and provides many methods for printing data to standard out, including println(String) which also appends a new line to the passed string.

The string "Hello World!" is automatically converted to a String object by the compiler.