Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Friday, September 17, 2010

Modifying Java Variables (w.r.t c and c++)

Modifying Simple Variable
The only mechanism for changing the value of a simple Java variable is an assignment statement. Java assignment syntax is identical to C assignment syntax. As in C, an assignment replaces the value of a variable named on the left- hand side of the equals sign by the value of the expression on the right- hand side of the equals sign.

Modifying Object Variable 
Java object variables can be changed in two ways. Like simple variables, you can make assignments to object variables. When this is done the object referenced by the variable is not changed. Instead, the reference is replaced by a reference to a different object.
With a few exceptions, the only other thing that you can do with an object variable is to send it a message. This is an important part of any Java program, allowing communication between objects.


Wednesday, September 15, 2010

Java and CPP - the differences and similarities

This list of similarities and differences is based heavily on The Java Language Environment, A White Paper by James Gosling and Henry McGilton http://java.sun.com/doc/language_environment/ and the soon-to-be published book, Thinking in Java by Bruce Eckel, http://www.EckelObjects.com/. At least these were the correct URLs at one point in time. Be aware, however, that the web is a dynamic environment and the URLs may change in the future.
Java does not support typedefs, defines, or a preprocessor. Without a preprocessor, there are no provisions for including header files.
Since Java does not have a preprocessor there is no concept of #define macros or manifest constants. However, the declaration of named constants is supported in Java through use of the final keyword.
Java does not support enums but, as mentioned above, does support named constants.
Java supports classes, but does not support structures or unions.
All stand-alone C++ programs require a function named main and can have numerous other functions, including both stand-alone functions and functions, which are members of a class. There are no stand-alone functions in Java. Instead, there are only functions that are members of a class, usually called methods. Global functions and global data are not allowed in Java.
All classes in Java ultimately inherit from the Object class. This is significantly different from C++ where it is possible to create inheritance trees that are completely unrelated to one another.
All function or method definitions in Java are contained within the class definition. To a C++ programmer, they may look like inline function definitions, but they aren't. Java doesn't allow the programmer to request that a function be made inline, at least not directly.
Both C++ and Java support class (static) methods or functions that can be called without the requirement to instantiate an object of the class.
The interface keyword in Java is used to create the equivalence of an abstract base class containing only method declarations and constants. No variable data members or method definitions are allowed. (True abstract base classes can also be created in Java.) The interface concept is not supported by C++.
Java does not support multiple inheritance. To some extent, the interface feature provides the desirable features of multiple inheritance to a Java program without some of the underlying problems.
While Java does not support multiple inheritance, single inheritance in Java is similar to C++, but the manner in which you implement inheritance differs significantly, especially with respect to the use of constructors in the inheritance chain.
In addition to the access specifiers applied to individual members of a class, C++ allows you to provide an additional access specifier when inheriting from a class. This latter concept is not supported by Java.
Java does not support the goto statement (but goto is a reserved word). However, it does support labeled break and continue statements, a feature not supported by C++. In certain restricted situations, labeled break and continue statements can be used where a goto statement might otherwise be used.
Java does not support operator overloading.
Java does not support automatic type conversions (except where guaranteed safe).
Unlike C++, Java has a String type, and objects of this type are immutable (cannot be modified). Quoted strings are automatically converted into String objects. Java also has a StringBuffer type. Objects of this type can be modified, and a variety of string manipulation methods are provided.
Unlike C++, Java provides true arrays as first-class objects. There is a length member, which tells you how big the array is. An exception is thrown if you attempt to access an array out of bounds. All arrays are instantiated in dynamic memory and assignment of one array to another is allowed. However, when you make such an assignment, you simply have two references to the same array. Changing the value of an element in the array using one of the references changes the value insofar as both references are concerned.
Unlike C++, having two "pointers" or references to the same object in dynamic memory is not necessarily a problem (but it can result in somewhat confusing results). In Java, dynamic memory is reclaimed automatically, but is not reclaimed until all references to that memory become NULL or cease to exist. Therefore, unlike in C++, the allocated dynamic memory cannot become invalid for as long as it is being referenced by any reference variable.
Java does not support pointers (at least it does not allow you to modify the address contained in a pointer or to perform pointer arithmetic). Much of the need for pointers was eliminated by providing types for arrays and strings. For example, the oft-used C++ declaration char* ptr needed to point to the first character in a C++ null-terminated "string" is not required in Java, because a string is a true object in Java.
A class definition in Java looks similar to a class definition in C++, but there is no closing semicolon. Also forward reference declarations that are sometimes required in C++ are not required in Java.
The scope resolution operator (::) required in C++ is not used in Java. The dot is used to construct all fully-qualified references. Also, since there are no pointers, the pointer operator (->) used in C++ is not required in Java.
In C++, static data members and functions are called using the name of the class and the name of the static member connected by the scope resolution operator. In Java, the dot is used for this purpose.
Like C++, Java has primitive types such as int, float, etc. Unlike C++, the size of each primitive type is the same regardless of the platform. There is no unsigned integer type in Java. Type checking and type requirements are much tighter in Java than in C++.
Unlike C++, Java provides a true boolean type.
Conditional expressions in Java must evaluate to boolean rather than to integer, as is the case in C++. Statements such as if(x+y)... are not allowed in Java because the conditional expression doesn't evaluate to a boolean.
The char type in C++ is an 8-bit type that maps to the ASCII (or extended ASCII) character set. The char type in Java is a 16-bit type and uses the Unicode character set (the Unicode values from 0 through 127 match the ASCII character set). For information on the Unicode character set see http://www.stonehand.com/unicode.html.
Unlike C++, the >> operator in Java is a "signed" right bit shift, inserting the sign bit into the vacated bit position. Java adds an operator that inserts zeros into the vacated bit positions.
C++ allows the instantiation of variables or objects of all types either at compile time in static memory or at run time using dynamic memory. However, Java requires all variables of primitive types to be instantiated at compile time, and requires all objects to be instantiated in dynamic memory at runtime. Wrapper classes are provided for all primitive types except byte and short to allow them to be instantiated as objects in dynamic memory at runtime if needed.
C++ requires that classes and functions be declared before they are used. This is not necessary in Java.
The "namespace" issues prevalent in C++ are handled in Java by including everything in a class, and collecting classes into packages.
C++ requires that you re-declare static data members outside the class. This is not required in Java.
In C++, unless you specifically initialize variables of primitive types, they will contain garbage. Although local variables of primitive types can be initialized in the declaration, primitive data members of a class cannot be initialized in the class definition in C++.
In Java, you can initialize primitive data members in the class definition. You can also initialize them in the constructor. If you fail to initialize them, they will be initialized to zero (or equivalent) automatically.
Like C++, Java supports constructors that may be overloaded. As in C++, if you fail to provide a constructor, a default constructor will be provided for you. If you provide a constructor, the default constructor is not provided automatically.
All objects in Java are passed by reference, eliminating the need for the copy constructor used in C++.
(In reality, all parameters are passed by value in Java.  However, passing a copy of a reference variable makes it possible for code in the receiving method to access the object referred to by the variable, and possibly to modify the contents of that object.  However, code in the receiving method cannot cause the original reference variable to refer to a different object.)
There are no destructors in Java. Unused memory is returned to the operating system by way of a garbage collector, which runs in a different thread from the main program. This leads to a whole host of subtle and extremely important differences between Java and C++.
Like C++, Java allows you to overload functions. However, default arguments are not supported by Java.
Unlike C++, Java does not support templates. Thus, there are no generic functions or classes.
Unlike C++, several "data structure" classes are contained in the "standard" version of Java. More specifically, they are contained in the standard class library that is distributed with the Java Development Kit (JDK). For example, the standard version of Java provides the containers Vector and Hashtable that can be used to contain any object through recognition that any object is an object of type Object. However, to use these containers, you must perform the appropriate upcasting and downcasting, which may lead to efficiency problems.
Multithreading is a standard feature of the Java language.
Although Java uses the same keywords as C++ for access control: private, public, and protected, the interpretation of these keywords is significantly different between Java and C++.
There is no virtual keyword in Java. All non-static methods always use dynamic binding, so the virtual keyword isn't needed for the same purpose that it is used in C++.
Java provides the final keyword that can be used to specify that a method cannot be overridden and that it can be statically bound. (The compiler may elect to make it inline in this case.)
The detailed implementation of the exception handling system in Java is significantly different from that in C++.
Unlike C++, Java does not support operator overloading. However, the (+) and (+=) operators are automatically overloaded to concatenate strings, and to convert other types to string in the process.
As in C++, Java applications can call functions written in another language. This is commonly referred to as native methods. However, applets cannot call native methods.
Unlike C++, Java has built-in support for program documentation. Specially written comments can be automatically stripped out using a separate program named javadoc to produce program documentation.
Generally Java is more robust than C++ due to the following:
  • Object handles (references) are automatically initialized to null.
  • Handles are checked before accessing, and exceptions are thrown in the event of problems.
  • You cannot access an array out of bounds.
  • Memory leaks are prevented by automatic garbage collection.

C++ ACCESSORS AND MUTATORS TUTORIAL

• I. INTRODUCTION

Hello; nice to meet you! Welcome to the “C++ Accessors and Mutators Tutorial.”

The tutorial assumes you are familiar with the following vocabulary:

1. Instantiation is declaring an object of a class type.

2. Encapsulation is the idea of an object containing data and functions that operate on that data.

3. A class is a user defined type.

4. Inheritance allows the creation of hierarchical classifications.

5. Polymorphism is Greek for “many shapes;” which becomes manipulating “many types” through a common interface. Polymorphism gives a programmer “programming in the general” instead of “programming in the specific.”

6. Object-oriented programming (OOP) is the use of inheritance, run-time polymorphism, encapsulation, and the programming style of defining your own data types as classes.

• II. PRIVATE DATA MEMBERS

The variables declared as part of the class are data members. Data hiding occurs when access control is established by data members being declared in the private area of the body of a class definition. The private access specifier prevents direct access to the class data members. However, private data members can be accessed indirectly by public accessor and mutator member functions and friends of that class.

• III. CONSTRUCTORS

When data members are declared they can not be initialized in the class body. Therefore, constructors are used to initialize the class data members when the class objects are instantiated.

• IV. GOOD ACCESSOR CHARACTERISTICS

Accessors or get functions:

1. Read or obtain the value of private member variables.

This must be done in a manner that maintains the integrity of the private member data.

2. Display the value of private member variables.

The displayed information should be user friendly, i.e., formatted in a fashion easily readable and understandably by the user.

3. Print the value of private member variables.

When an inappropriate attempt is made to change the value of a private data member, a properly written get function with good characteristics will be programmed to notify the user. User management should receive written notification of all inappropriate activity as soon as it occurs.

• V. GOOD MUTATOR CHARACTERISTICS

Mutators or set functions:

1. Modify the value of private data members.

Public set functions set the value of private data members. However, set functions should not just change data. Set functions must be programmed to make sure what they are being called to do is correct before they do it. Properly written set functions are the first line of defense against, “garbage in, garbage out.”

2. Validate the value of private data members.

When an inappropriate attempt is made to change the value of a private data member, a properly written set function will be programmed to prevent the modification.

• VI. ADVANTAGES OF USING GET AND SET FUNCTIONS

The main advantages of always using get and set public class member functions is faster, more efficient, and less expensive program maintenance.

1. All data usage updates only have to be made to the appropriate public get member functions.

2. All data value storage updates only have to be made to the appropriate public set member functions.

• VII. SUMMARY

The names of the accessor and mutator member functions do not have to begin with get and set; however, the naming convention is a generally accepted programming practice.

In general, get and set functions are a public interface for read/write access to private data members.

Even though all class member functions can indirectly access private data members, the programmer should ensure the program is written so that all member functions call the appropriate get and set functions when interacting with private data members.

Wednesday, July 28, 2010

Inheritance

Inheritance
Inheritance is similar in Java and C++. Java uses the extends keyword instead of the : token. All inheritance in Java is public inheritance; there is no analog to the C++ features of private and protected inheritance.

Calling base class constructor
In java, we can use super keyword.

super(parameter-list);

eg.
//X is super class, with attributes width, height, depth and has constructor for 3 attributes.

class Y extends X
{
  double weight; // weight of box
  // initialize width, height, and depth using super()
  Y(double w, double h, double d, double m) {
  super(w, h, d); // call superclass constructor
  weight = m;
   }
}

2nd use of super in java

The second form of super acts somewhat like this, except that it always refers to 

the



 superclass of the subclass in which it is used. This usage has the following 

general form:









super.member

Here, member can be either a method or an instance variable.
eg.
// Using super to overcome name hiding.
class A {
int i;
}
// Create a subclass by extending class A.
class B extends A {
int i; // this i hides the i in A
  B(int a, int b) {
   super.i = a; // i in A
   i = b; // i in B
  }
  void show() {
    System.out.println("i in superclass: " + super.i);
    System.out.println("i in subclass: " + i);
   }
}

Multilevel inheritance - Base class constructor is called 1st.



// Demonstrate when constructors are called.




// Create a super class.
class A {
A() {
System.out.println("Inside A's constructor.");
}
}
// Create a subclass by extending class A.
class B extends A {
B() {
System.out.println("Inside B's constructor.");
}
}
// Create another subclass by extending B.
class C extends B {
C() {
System.out.println("Inside C's constructor.");
}
}
class CallingCons {
public static void main(String args[]) {
C h a p t e r 8 : I n h e r i t a n c e 207
THE JAVA LANGUAGE
C c = new C();
}
}
The output from this program is shown here:
Inside A’s constructor
Inside B’s constructor
Inside C’s constructor




Tuesday, December 15, 2009

Abstract classes

In CPP


A class that contains at least one pure virtual function is said to be abstract. Because an
abstract class contains one or more functions for which there is no definition (that is, a
pure virtual function), no objects of an abstract class may be created. Instead, an
abstract class constitutes an incomplete type that is used as a foundation for derived
classes.
Although you cannot create objects of an abstract class, you can create pointers and
references to an abstract class. This allows abstract classes to support run-time
polymorphism, which relies upon base-class pointers and references to select the
proper virtual function.

JAVA

Wednesday, August 13, 2008

User defined data types

C supports following
typedef
struct
enum

cpp adds following :
classes

typedef
C support the feature known as type definition that allows user to define an identifier that would represent an exiting data type. The user defined datatype isentifier can later be used to declare variables. It takes the general form.
typedef type identifier;
Where type refers to an existing data type may belong to any class of type , including the user defined ones. Remember that the new type is 'new' only in name , but not the data type. typedef can not create a new type. Some example of type definition are :
typedef int units;
typedef float marks; 
Here , unit symbolizes int and mark symbolizes folat. They can be later used to declare variables as follows.
units batch1, batch2;
 marks name1[50], name2[50];
Enum
Consider the following PPD = #define
#define APPLE 1 OR const int APPLE = 1;//in cpp
#define PEAR 2
#define PEACH 3
#define PLUM 4
The C preprocessor processes all C and C++ files before the compiler is called. The C preprocessor will fill in the defined value for every occurance of the define name. So where ever PEAR appears in the code, the C preprocessor will fill in 2.
While #define constants are better than just using unnamed numeric values, this is a crude way to define a set of values. Later versions of C added enumerations, which are also in C++. Here is the syntax:
enum { single, married, divorced, widower};
enum mar_status { single, married, divorced, widower};
Here single has value = 0 , rest increase by 1.
An example of a C++ enumeration, defining the same values is shown below:
typedef enum { APPLE = 1, PEAR, PEACH, PLUM } fruit;
In C++ enumerations also got a thin veneer of type safety. To convert an enumeration to an integer it was necessary to use a cast.
fruit basket = (fruit)42;
The range for enumeration values is not enforced in C++, so the statement above compiles without error, even though 42 is beyond the enumeration range. In C++ enumeration values can also be assigned to integers without a cast operation:
int y = PLUM;
Java does not provide an enumeration type, so it is tempting to use something like the C #define. For example:
class StateMachine
{
public static final int WAIT = 1;
public static final int NICKLE = 2;
public static final int DIME = 3;
public static final int QUARTER = 4;
....
private int currentState = WAIT;
}


Examples:
1. enum { v1 = -1, v2, v3=6, v4, v5, v6, v7} var;
printf("%d" , sizeof(var));
O
2(DOS)
4(VC++)
2. printf2(v1, v2, v3, v4, v5, v6, v7);
O
-1 0 6 7 8 9
3. Operators like ++ don't work, because enum are const int.
printf2(++v1);
O.
error

Unions
 A union is a variable which may hold (at different times) objects of different sizes and types. That is a union hold only one member at a time. C uses the union statement to create unions, for example.

 union number 
   {
     short shortnumber;
     long longnumber;
     double floatnumber;
   } anumber
defines a union called number and an instance of it called a number. number is a union tag and acts in the same way as a tag for a Structure. All operation on union like that of Structure.

Difference between Structure and union is Structure allocate storage space for all the members where as union allow only one  member at a time. Application of union is when we need only one member of a Structure  for a particular application that time we can use union.