[go: up one dir, main page]

0% found this document useful (0 votes)
62 views22 pages

Comparison With C and C++: Major Implementations: Programming-Input /output

Download as doc, pdf, or txt
Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1/ 22

1.

COMPARISON WITH C AND C++


C C++

GNU Compiler Major GCC, MSVC, Borland C,Collection, Microsoft Implementations: Watcom C Visual C++, Borland C+ + Builder Programming-input scanf for input;printfcin for input;cout for /output: for output output C++ applications C applications are are generallyslower at faster to compile and Speed: runtime, and are much execute than C+ slower to compile +applications than C programs OOP(Object Yes-polymorphism and Oriented No inheritance Programming): Appeared in: 1972 1985 Designed by: Dennis Ritchie Bjarne Stroustrup Dennis Ritchie & Bell Developed by: Bjarne Stroustrup Labs Static, Unsafe, Typing Discipline: Static, Weak Nominative Programminguse #include use #include<stdio.h> include: <iostream.h> Cannot use string type Programmingbut declare it as anCan use string type String type: array

C++, as the name suggests is a superset of C. As a matter of fact, C++ can run most of C code while C cannot run C++ code. Here are the 10 major differences between C++ & C 1. C follows the procedural programming paradigm while C++ is a multiparadigm language(procedural as well as object oriented) In case of C, importance is given to the steps or procedure of the program while reason. 2. In case of C, the data is not secured while the data is secured(hidden) in C++ This difference is due to specific OOP features like Data Hiding which are not present in C. 3. C is a low-level language while C++ is a middle-level language C is regarded as a low-level language(difficult interpretation & less user friendly) while C++ has features of both low-level(concentration on whats going on in the machine hardware) & high-level languages(concentration on the program itself) & hence is regarded as a middle-level language. 4. C uses the top-down approach while C++ uses the bottom-up approach In case of C, the program is formulated step by step, each step is processed into detail while in C++, the base elements are first formulated which then are linked together to give rise to larger systems. 5. C is function-driven while C++ is object-driven C++ focuses on the data rather than the process. Also, it is easier to implement/edit the code in case of C++ for the same

Functions are the building blocks of a C program while objects are building blocks of a C++ program. 6. C++ supports function overloading while C does not Overloading means two functions having the same name in the same program. This can be done only in C++ with the help of Polymorphism(an OOP feature) 7. We can use functions inside structures in C++ but not in C. In case of C++, functions can be used inside a structure while structures cannot contain functions in C. 8. The NAMESPACE feature in C++ is absent in case of C C++ uses NAMESPACE which avoid name collisions. For instance, two students enrolled in the same university cannot have the same roll number while two students in different universities might have the same roll number. The universities are two different namespace & hence contain the same roll number(identifier) but the same university(one namespace) cannot have two students with the same roll number(identifier) 9. The standard input & output functions differ in the two languages C uses scanf & printf while C++ uses cin>> & cout<< as their respective input & output functions 10. C++ allows the use of reference variables while C does not Reference variables allow two variable names to point to the same memory location. We cannot use these variables in C programming.

JDK (Java Development Kit)

Java Developer Kit contains tools needed to develop the Java programs, and JRE to run the programs. The tools include compiler (javac.exe), Java application launcher (java.exe), Applet viewer, etc Compiler converts java code into byte code. Java application launcher opens a JRE, loads the class, and invokes its main method. You need JDK, if at all you want to write your own programs, and to compile the m. For running java programs, JRE is sufficient. JRE is targeted for execution of Java files i.e. JRE = JVM + Java Packages Classes(like util, math, Lang, awt,swing etc)+runtime libraries. JDK is mainly targeted for java development. I.e. You can create a Java file (with the help of Java packages), compile a Java file and run a java file JRE (Java Runtime Environment) Java Runtime Environment contains JVM, class libraries, and other supporting files. It does not contain any development tools such as compiler, debugger, etc. Actually JVM runs the program, and it uses the class libraries, and other supporting files provided in JRE. If you want to run any java program, you need to have JRE installed in the system The Java Virtual Machine provides a platform-independent way of executing code; programmers can concentrate on writing software, without having to be concerned with how or where it will run. If u just want to run applets (ex: Online Yahoo games or puzzles), JRE needs to be installed on the machine. JVM (Java Virtual Machine) As we all aware when we compile a Java file, output is not an 'exe' but it's a '.class' file. '.class' file consists of Java byte codes which are understandable by JVM. Java Virtual Machine interprets the byte code into the machine code depending upon the underlying operating system and hardware combination. It is responsible for all the things like garbage collection, array bounds checking, etc JVM is platform dependent. The JVM is called "virtual" because it provides a machine interface that does not depend on the underlying operating system and machine hardware

architecture. This independence from hardware and operating system is a cornerstone of the write-once run-anywhere value of Java programs. There are different JVM implementations are there. These may differ in things like performance, reliability, speed, etc. These implementations will differ in those areas where Java specification doesnt mention how to implement the features, like how the garbage collection process works is JVM dependent, Java spec doesnt define any specific way to do this.

1) Java 1.6 runs faster than Java 1.5. 2) Java 1.6 makes programming easier by implementing various tools such as Swing Worker and JTable to develop user interface. 3) Java 1.6 includes new or, in some cases, improved monitoring and management tools, including the "infamous" That, which is used to explore core dumps. It also includes more diagnostic information, making bug fixing somewhat easier.

4) In java 1.6, Java DB, a new database management tool has been included. Java DB is based on the open-source Apache Derby and is supported by Sun.

OOPs and Its Concepts in Java

Object Oriented Programming or OOP is the technique to create programs based on the real world. Unlike procedural programming, here in the OOP programming model programs are organized around objects and data rather than actions and logic. Objects represent some concepts or things and like any other objects in the real Objects in programming language have certain behavior, properties, type, and identity. In OOP based language the principal aim is to find out the objects to manipulate and their relation between each

other. OOP offers greater flexibility and compatibility and is popular in developing larger application. Another important work in OOP is to classify objects into different types according to their properties and behavior. So OOP based software application development includes the analysis of the problem, preparing a solution, coding and finally its maintenance. Java is a object oriented programming and to understand the functionality of OOP in Java, we first need to understand several fundamentals related to objects. These include class, method, inheritance, encapsulation,

abstraction, polymorphism etc. Class - It is the central point of OOP and that contains data and codes with behavior. In Java everything happens within class and it describes a set of objects with common behavior. The class definition describes all the properties, behavior, and identity of objects present within that class. As far as types of classes are concerned, there are predefined classes in languages like C++ and Pascal. But in Java one can define his/her own types with data and code. Object - Objects are the basic unit of object orientation with behavior, identity. As we mentioned above, these are part of a class but are not the same. An object is expressed by the variable and methods within the objects. Again these variables and methods are distinguished from each other as instant variables, instant methods and class variable and class methods.

Methods - We know that a class can define both attributes and behaviors. Again attributes are defined by variables and behaviors are represented by methods. In other words, methods define the abilities of an object. Inheritance - This is the mechanism of organizing and structuring software program. Though objects are distinguished from each other by some additional features but there are objects that share certain things common. In object oriented programming classes can inherit some common behavior and state from others. Inheritance in OOP allows to define a general class and later to organize some other classes simply adding some details with the old class definition. This saves work as the special class inherits all the properties of the old general class and as a programmer you only require the new features. This helps in a better data analysis, accurate coding and reduces development time. Abstraction - The process of abstraction in Java is used to hide certain details and only show the essential features of the object. In other words, it deals with the outside view of an object (interface). Encapsulation - This is an important programming concept that assists in separating an object's state from its behavior. This helps in hiding an object's data describing its state from any further modification by external component. In Java there are four different terms used for hiding data constructs and these are public, private, protected and package. As we know an object can associated with data with predefined classes and in any application an object can know about the data it needs to know about. So

any unnecessary data are not required by an object can be hidden by this process. It can also be termed as information hiding that prohibits outsiders in seeing the inside of an object in which abstraction is implemented. Polymorphism - It describes the ability of the object in belonging to different types with specific behavior of each type. So by using this, one object can be treated like another and in this way it can create and define multiple level of interface. Here the programmers need not have to know the exact type of object in advance and this is being implemented at runtime.

In Java, some of the differences between other methods and constructors are:

Constructors Constructors used). Constructors Constructors

never have an explicit return type. cannot be directly invoked (the keyword new must be cannot be synchronized, final, abstract, native, or static. are always executed by the same thread.

This Keyword You cannot use this inside a static block because this relates to an instance of a class ("this instance"), while static blocks belong to the class itself. So, which one is the this instance when you're inside a block that does not belong specifically to any instance? In the case of your program, the static block is executed when the class is loaded, that's why the first output you see is "Static block started". Then, instance data is initialized. Is that clear?

The keyword this is useful when you need to refer to instance of the class from its method. The keyword helps us to avoid name conflicts. As we can see in the program that we have declare the name of instance variable and local variables same. Now to avoid the confliction between them we use this keyword. Super keyword This super key word is used to call a method in protected access modifier as we know the protected modifiers cannot accessible from any other package or classes without having inheritance by using the super keyword, compiler identifies the protected method of another class is available in current class as the method has being inherited in current class also the compiler will not allow to reference an object from another class which has Protected access. Use same class reference and call method () it is possible as the Obj class is inherited. *

Super keyword

The super is java keyword. As the name suggest super is used to access the members of the super class. It is used for two purposes in java. The first use of keyword super is to access the hidden data variables of the super class hidden by the sub class. E.g. Suppose class A is the super class that has two instance variables as int a and float b. class B is the subclass that also contains its own data members named a and b. then we can access the super class (class A) variables a and b inside the subclass class B just by calling the following command. Super. Member; Here member can either be an instance variable or a method. This form of super most useful to handle situations where the local members of a subclass hide the members of a super class having the same name.

class A{ int a; float b; void Show(){ System.out.println("b in super class: } } class B extends A{ int a; float b;

" + b);

B( int p, float q){ a = p; super.b = q; } void Show(){ super.Show(); System.out.println("b in super class: " + super.b); System.out.println("a in sub class: " + a); } public static void main(String[] args){ B subobj = new B(1, 5); subobj.Show(); } }

class A{ int a; int b; int c; A(int p, int q, int r){ a=p; b=q; c=r; } } class B extends A{ int d; B(int l, int m, int n, int o){ super(l,m,n); d=o; } void Show(){ System.out.println("a = " + a); System.out.println("b = " + b); System.out.println("c = " + c); System.out.println("d = " + d); }

public static void main(String args[]){ B b = new B(4,3,8,7); b.Show(); } }

11.1 The Causes of Exceptions An exception is thrown for one of three reasons: An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.

An abnormal execution condition was synchronously detected by the Java virtual machine. Such conditions arise because: o evaluation of an expression violates the normal semantics of the language, such as an integer divide by zero, as summarized in 15.6 o an error occurs in loading or linking part of the program (12.2, 12.3) o some limitation on a resource is exceeded, such as using too much memory These exceptions are not thrown at an arbitrary point in the program, but rather at a point where they are specified as a possible result of an expression evaluation or statement execution.

A throw statement (14.17) was executed. An asynchronous exception occurred either because: o the method stop of class Thread was invoked o an internal error has occurred in the virtual machine (11.5.2)

Exceptions are represented by instances of the class Throwable and instances of its subclasses. These classes are, collectively, the exception classes. Subclass of runtime Exception is unchecked exception, remaining things are checked exception

Checked vs. Unchecked Exceptions Type of exceptions in java is checked exceptions and unchecked exceptions. This classification is based on compile-time checking of exceptions. There is also a classification based on runtime in java. It is not widely known! That is synchronous and asynchronous exceptions. First let us see the java checked exceptions and unchecked exceptions. Checked Exceptions Vs Unchecked Exceptions in Java At compile time, the java compiler checks that a program contains handlers for checked exceptions. Java compiler analyzes by which checked exceptions can result from execution of a method or constructor. For each checked

exception which is a possible result, the throws clause for the method or constructor must mention the class or its super classes of that exception. The class Runtime Exception and its subclasses, and the class Error and its subclasses are unchecked exceptions classes. Because the compiler doesnt forces them to be declared in the throws clause. All the other exception classes that are part of Throw able hierarchy are checked exceptions. Now let us see a see small discussion on why exceptions are classified as checked exceptions and unchecked exceptions. Those unchecked exception classes which are the error classes (Error and its subclasses) are exempted from compile-time checking in java because they can occur at many points in the program and recovery from them is difficult or impossible. Example: OutOfMemoryError Thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector. The runtime exception classes (Runtime Exception and its subclasses) are exempted from compile-time checking because, in the judgment of the designers of the Java, having to declare such exceptions would not aid significantly in establishing the correctness of programs. Example: NullPointerException Thrown when an application attempts to use null in a case where an object is required.

So the java compiler doesnt force them to be declared in the above two cases. Synchronous and Asynchronous Exceptions in Java The interpreter executes the java program sequentially. An exception E can occur relative to a line (L) of program. That is that exception E will always occur at the execution of that line L. This is called Synchronous exception. An asynchronous exception in java can occur at any point in the execution of a program. They occur only as a result of: 1. An invocation of the stop methods of class Thread or Thread Group 2. An internal error in the Java virtual machine

EXCEPTIONS Arithmetic Exception

DESCRIPTION Arithmetic errors such as a divide by zero Arrays index is not within array.length Related Class not found

CHECKED -

UNCHECKED YES

ArrayIndexOutOfBoundsException

YES

ClassNotFoundException IO Exception

YES

InputOuput field not YES found

IllegalArgumentException

Illegal argument when calling a method

YES

Interrupted Exception

One thread has been interrupted by YES another thread Nonexistent method YES Invalid use of null reference -

NoSuchMethodException NullPointerException

YES

NumberFormatException

Invalid string for conversion to number

YES

String class objects work with complete strings instead of treating them as character arrays as some languages do. Note: Convert variables of type char to string objects by using gStr = Character.toString(c);. Accessor methods: length(), charAt(i), getBytes(), getChars(istart,iend,gtarget[],itargstart), split(string,delim), toCharArray(), valueOf(g,iradix), substring(iStart [,iEndIndex)]) [returns up to but not including iEndIndex] Modifier methods: concat(g), replace(cWhich, cReplacement), toLowerCase(), toUpperCase(), trim(). Note: The method format(gSyn,g) uses c-like printf syntax for fixed fields if required in reports. Boolean test methods: contentEquals(g), endsWith(g), equals(g), equalsIgnoreCase(g), matches(g), regionMatches(i1,g2,i3,i4), regionMatches(bIgnoreCase,i1,g2,i3,i4), startsWith(g) Integer test methods: compareTo(g) [returns 0 if object equals parameter, -1 if object is before parameter in sort order, +1 if otherwise], indexOf(g) [returns position of first occurrence of substring g in the string, -1 if not found], lastIndexOf(g) [returns position of last occurrence of substring g in the string, -1 if not found], length(). String class objects are immutable (ie. read only). When a change is made to a string, a new object is created and the old one is disused. This causes extraneous garbage collection if string modifier methods are used too often. TheStringBuffer or StringBuilder class should be used instead of String objects in these cases.

StringBuffer class objects allow manipulation of strings without creating a new object each time a manipulation occurs ccessor methods: capacity(), charAt(i), length(), substring(iStart [,iEndIndex)]) Modifier methods: append(g), delete(i1, i2), deleteCharAt(i), ensureCapacity(), getChars(srcBeg, srcEnd, target[], targetBeg), insert(iPosn, g), replace(i1,i2,gvalue), reverse(), setCharAt(iposn, c), setLength(),toString(g)

StringBuilder class methods are similar to StringBuffer ones but they are unsynchronized (ie. not for multithreaded applications). They are also much faster. Examples of setting up a string buffer variable are: Accessor methods: capacity(), length(), charAt(i), indexOf(g), lastIndexOf(g) Modifier methods: append(g), delete(i1, i2), insert(iPosn, g), getChars(i), setCharAt(iposn, c), substring(), replace(i1,i2,gvalue), reverse(), trimToSize(g ), toString(g)

Many text manipulation utilities require a tokenizer function which parses or breaks up the text into subunits calledtokens based on specific delimiters or break characters. The most common delimiter is whitespace which yields words as the tokens. The String.split(string, reg_exp) method allows regular expressions to be used to define the delimiters. Java also provides several tokenizer classes including StringTokenizer for strings, StreamTokenizer for files, and Scanner class for files using regular expression delimiters. StringTokenizer class objects may be created by one of three constructor methods depending on the parameters used. The first parameter string is the source text to be broken at the default set of whitespace delimiters (space, tab, newline, cr, formfeed). If a second parameter is passed, that string is assumed to be the set of delimiting characters. Use the escaper \ character when representing the string quote character " or any nontypeable delimiters such as tab (\t). If a true flag is added as a third parameter, any delimiters found are also returned as string tokens. The StringTokenizer methods are: int countTokens(), boolean hasMoreTokens() and String nextToken().

THREAD
Thread is the feature of mostly languages including Java. Threads allow the program to perform multiple tasks simultaneously. Process speed can be increased by using threads because the thread can stop or suspend a specific running process and start or resume the suspended processes. Multitasking or multiprogramming is delivered through the running of multiple threads concurrently. If your computer does not have multiprocessors then the multi-threads really do not run concurrently.

In java we have two types of Threads: Daemon Thread and User Threads. Generally all threads created by programmer are user thread (unless you specify it to be daemon or your parent thread is a daemon thread). User thread is generally meant to run our program code. JVM doesn't terminate unless all the user thread terminate. On the other hand we have Daemon threads. Typically these threads are service provider threads. They should not be used to run your program code but some system code. These threads run parallel to your code but survive on the mercy of the JVM. When JVM finds no user threads it stops and all daemon thread terminate instantly. Thus one should never rely on daemon code to perform any program code. For better understanding consider a well known example of Daemon thread: Java garbage collector. Garbage collector runs as a daemon thread to reclaim any unused memory. When all user threads terminates, JVM may stop and garbage collector also terminates instantly.

The static synchronized methods of the same class always block each other as only one lock per class exists. So no two static synchronized methods can execute at the same time. When a synchronized non static method is called a lock is obtained on the object. When a synchronized static method is called a lock is obtained on the class and not on the object.

every instance of class Object and its subclass's has a lock primitive data type fields (Scalar fields) can only be locked via their enclosing class fields cannot be marked as synchronized however they can be declared volatile which orders the way they can be used or you can write synchronized access or methods array objects can be synchronized BUT their elements cannot, nor can their elements be declared volatile Class instances are Objects and can be synchronized via static synchronized methods Synchronized blocks allow you to execute synchronized code that locks an object without requiring you to invoke a synchronized method Synchronized ( expr ) { // 'expr' must evaluate to an Object } Synchronized methods declaring a method as synchronized ie synchronized void f() is equivalent to void f() { synchronized(this) { // body of method } } the synchronized keyword is NOT considered part of a method's signature. IT IS NOT AUTOMATICALLY INHERITED when subclasses override superclass methods methods in Interfaces CANNOT be declared synchronized constructors CANNOT be declared synchronized however they can contain synchronized blocks synchronized methods in subclasses use the same locks as their superclasses synchronization of an Inner Class is independent on it's outer class a non-static inner class method can lock it's containing class by using a synchronized block synchronized(OuterClass.this) { // body } Locking locking follows a built-in acquire-release protocol controlled by the synchronized keyword a lock is acquired on entry to a synchronized method or block and released on exit, even if the exit is the result of an exception you cannot forget to release a lock locks operate on a per thread basis, not on a per-invocation basis

Java uses re-entrant locks ie a thread cannot lock on itself class Reentrant {

public synchronized void a() { b(); System.out.println("here I am, in a()"); } public synchronized void b() { System.out.println("here I am, in b()"); } } in the above code, the synchronized method a(), when executed, obtains a lock on its own object. It then calls synchronized method b() which also needs to acquire a lock on its own object if Java did not allow a thread to reacquire its own lock method b() would be unable to proceed until method a() completed and released the lock; and method a() would be unable to complete until method b() completed. Result: deadlock as Java does allow reentrant locks, the code compiles and runs without a problem the locking protocol is only followed for synchronized methods, it DOES NOT prevent unsynchronized methods from accessing the object once a thread releases a lock, another thread may acquire it BUT there is no guarantee as to WHICH thread will acquire the lock next Class fields and methods locking an object does not automatically protect access to static fields protecting static fields requires a synchronized static block or method static synchronized statements obtain a lock on the Class vs an instance of the class a synchronized instance method can obtain a lock on the class Synchronized (Class Name. class) { // body } the static lock on a class is not related to any other class including its super classes a lock on a static method has no effect on any instances of that class (JPL pg 185) you cannot effectively protect static fields in a super class by adding a new static synchronized method in a subclass; an explicit block synchronization is the preferred way

nor should you use synchronized(get Class()); this locks the actual Class which might be different from the class in which the static fields are declared

You might also like