Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
111 views

Internet Programming Unit 1 (In-Complete)

Java is an object-oriented programming language created by Sun Microsystems in 1991. It was originally called Oak but was renamed to Java in 1995. Key developments included demonstrating Java's use for controlling home appliances in 1992, the release of the Java programming language in 1995, and the establishment of Java as a leader for both internet and general purpose programming by 1996. Java's main features include being compiled and interpreted, platform independent and portable, object-oriented, and robust and secure.

Uploaded by

zayeem Neji
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
111 views

Internet Programming Unit 1 (In-Complete)

Java is an object-oriented programming language created by Sun Microsystems in 1991. It was originally called Oak but was renamed to Java in 1995. Key developments included demonstrating Java's use for controlling home appliances in 1992, the release of the Java programming language in 1995, and the establishment of Java as a leader for both internet and general purpose programming by 1996. Java's main features include being compiled and interpreted, platform independent and portable, object-oriented, and robust and secure.

Uploaded by

zayeem Neji
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

INTERNET PROGRAMMING USING JAVA

UNIT 1 – JAVA EVOLUTION


Internet:

It is a global network of networks. Or Internet is the largest computer network in the world connecting
billions of computers.

It uses the standard internet protocol suit called TCP/IP to serve billions of user worldwide.

 It consists of millions of private, public, business and government networks.

The internet is different from all other two aspects

1. It is the biggest network in the world.

2. It is freely accessible to the public.

The internet carries vast range of information resources and services.

History of Internet The first internet was developed by “Advance Research Product Agency”[ARPA] of US
department of defense in 1969. It has called as ARPA Net.

Difference between Internet and Intranet

Internet Intranet
It is a wide network of computers and it’s open for Intranet is also a network of computers design for
all.
Internet itself contains a large no of intranets. aIt specific
can be group of users.from internet but with
accessed
restrictions.
The number of users who use internet is unlimited. The number of users is limited.
The visitor’s traffic is unlimited. The traffic allowed is also limited
Internet contains different sources of information Intranet contain only specific group of information
and
It is aiscollection
available for all.
of various LAN, WAN and MAN. Mostly any of LAN or MAN or WAN
TCP = Transmission control protocol

IP = Internet protocol

Internet protocol : The internet protocol is the language that computers used to communicate over
the internet.

 Every machine on the internal as a unique identifying number called an IP address.

Example: 216.27.16.136

 The computers communicate in binary form.

Example: 11011000.00011011.00111101.10001000
If we add all the position together we get 32. so the IP address is always 32 bits.

 Some IP address Example : 0.0.0.0 is reserved for the default network.

 The address 255.255.255.255 is used for Broadcast.

 The most of the people type the domain name in the browser than IP address as it is easy to
remember name than numbers.

Example: IP address of www.google.com is 209.85.148.105

 The IP address of www.aimca.in is 14.139.159.35

Domain Names :

Domain names are textual names given to the notes on the internet. It is in the form of words
separated by dots[periods].

Example: www.google.com www.yahoo.org

The last position of domain name represents top level domain or first level domains . There are several
hundred top levels of domain name as follows.

Domain name Assigned to


.com Commercial organization
.edu Education organization
.gov Government organization
.mil Military organization
.net Major network support center
.org Organization
Country code domain :

A unique two letter combinations for every country like .in for India, Au for Australia, Uk for united
kindom.etc.

Sub Domain : Sub domains are the third level domains that are used to organize the website contain in a
systematic manner.

They are just like folders and under root directly. ex : http:||www.kar.nic.in

World Wide Web [WWW] :

 The web is a system of interlink hyper text documents access via internet.

 It is developed by TIM BERNERS LEE in 1989 at CERN[European laboratory for physics].

 It is the information sharing model that is built on top of the internet.

 The web uses http protocol to transmit data over the internet.
 The web utilizes browser like google chrome to access the web documents called web pages that are
linked to each other via hyperlinks.

 Web document contains graphics sounds text and video.

Web Browser :

 A web browser is a software application used to locate and display the web pages

.  It is able to retrieve, find, view and send information over the internet.

 When request is made by our computer then that computer is called client and when the request gets
serve by another computer then that computer is called server.

 Some of the popular web browser all internet explorer, opera, mozillafirefox.

Primary functions of browser

 The browser understands the programming languages used towrite web pages and converts then to
readable and viewable documents.

 Web browser knows how to go to a web server on the internet and request a page.

Java Evolution
Java History
.

Java is a general-purpose, object-oriented programming language developed by Sun Microsystems


of USA in 1991. Originally callcd Oak by James Gosling. one of the inventors of the language. Java
was designed for the development of software for consumer electronic devices like fl’s.
VCRs, toasters and such other electronic machines. The goal had a strong impact on the
development team to make the language simple, portable and highly reliable. The Java
team which included Patrick Naughton discovered that the existing languages like C and
C++ had limitations in terms of both reliability and portability. However, they modeled their new
language Java on C and C++ but removed a number of features of C and C++ that were
considered as sources of problems and thus made Java a really simple, reliable, portable, and
powerful Language.
IMP
Java Milestones
Year Dewlopments
1990 Sun Micro Systcms decided to develop a special software that could be uscd to
manipulate consumer electronic devices. A team of Sun Microsystems pro ogrammcrs
headed by james goslings was formed to undertake this task
1991 After exploring the possibility of using the most popular object oriented language
C++, the team announced a new language named Oak”
1992 The team, known as Green Project team by Sun. demonstrated application of thcir
new language to control a list of home appliances using a handheld device with a tiny
____

touch-sensitive screen.

1993 The World Wide Web (WWW) appeared on the Internet and transformed the teit-based
Internet Into a graphical-rich environment. The green Protect team came up with the
idea of developing Web applets (tiny programs ) using the new language that could run
on all types of computers connected to Internet
1994 The team developed a Web browser Called ‘Hot Java to locate and run applets programs
on Internet. Hot java demonstrated the power of the new language. thus making it
instantly popular among the Internet users.
1995 Oak was renamed “Java”. due to some legal snags. Java is just a name and is not an
acronym. Many popular companies including Netscape and Microsoft announced their
support to java.
1996 Java established itself not only as a leader for internet programming but also as a
gencral-purpose, object-oriented programming language. Sun releases Java
development kit 1.0
1997 Sun releases Java development kit 1.1 (JDK 1.1)
1998 Sun releases Java 2 with venison 1.2 of the Software Development Kit (SDK 1.2
1999 Sun releases Java 2 Platform, Standard Edition (12SF) and Enterprise Edition (J2EE).
2000 J2SE with SDK 1.3 was released
2002 J2SE with SDK 1.4 was released

Java Features IMP


1. Compiled and Interpreted
Usually a computer language is either compiled or interpreted Java combines both these
approaches thus making Java a two-stage system. First. Java compiler translates source
codc into what is known as bytecode instructions. Bytecodes are not machine instructions
and therefore. in the second stage. Java interpreter generates machine code that can be
directly executed by the machine that is running the Java program. We can thus say that
Java is both a compiled and an interpreted language.
2. Platform-independent and Portable

The most significant contribution of Java over other languages is its portability. Java programs can
be easily moved from one computer system to another, anywhere and anytime. Changes and
upgrades in operating systems, processors and system resources will not force any changes in
Java programs. This is the reason why Java has become a popular language for programming on
Internet which interconnects different kinds of systems worldwide, We can download a Java
applet from a remote computer onto our local system via Internet and execute it locally. This
makes the Internet an extension of the user’s basic system providing practically unlimited number of
accessible applets and applications.

Java ensures portability in two ways. First, the java compiler generates code bytecode instructions
that can be implemented on any machine. Secondly, the size of the primitive data types
are machine- independent

3. Object-Oriented
Java ta a irue obje.nentd 1anguage. Almost eveything in Jara is an object. All program code and data
reside within objects and classes. Java comes with an extcnsivc sct of classes, arranged in packages,
that we can use in our programs by inheritance, The object model in Java is simple and easy to
extend

4. Robust and Secure


Java is a robust language. It provides many safeguards to ensure reliable code. it has strict compile
time and run time checking for data types. It is designed as a garbage-collected language relieving
the programmers virtually all memory management problems. Java also incorporates the concept
of exception handling which captures series of errors and eliminates any risk of crashing the system.

Security becomes an important issue for a language that is used for programming on Internet.
Threat of viruses and abuse of resources arc everywhere. Java systems not only verify all memory
access but also ensure that no viruscs are communicated with an applet. The absence of pointers
in Java ensures that programs cannot gain access to memory locations without proper
authorization

5. Distributed

Java is designed as a distributed language for creating applications on networks, It has the ability to
share both data and programs. Java applications can open and access remote objects on internet as
easily as they can do in a local system. This enables multiple programmers at multiple remote
locations to collaborate and work together on a single project
6. Simple, Small and Familiar

Java is a small and simple language. Many features of C and C+ that are either redundant or
sources of unreliable code are not part of Java. For example, Java does not use pointers,
preprocessor header files. goto statement and many others. It also eliminates operator
overloading and multiple inheritance.

Familiarity is another striking feature of Java. To make the language look familiar to the existing
programmers. it was modelled on C and C--+ languages. Java uses many constructs of C and
C++ and therefore Java code “looks Like a C++” code, In fact, java is a simplified version of
C++.

7. Multlthreaded and Interactive

Multithrcaded means handling multiple tasks simultaneously. Java supports multi-threaded


programs. ‘This means that we need not wait for the application to finish one task before beginning
another, For example, we can listen to an audio clip while scrolling a page and at the same
time download an applet from a distant computer. This fcaturc greatly improves the
interactive performance of graphical applications.
The Java runtime comes with tools that support multi-process synchronization and construct
smoothly running interactive systems

8. High Performance

Java performance is impressive for an interpreted language. mainly due to the use of intcrmediate
bytecode. According to Sun Java speed is comparable to the native C.’C’+ Java architecture is
.

also designed to reduce overheads during runtime Furthur. the incorporatioii of multithreading
enhances the overall execution speed of Java programs.
IMP
How Java Differs from C and C++
Although Java was modelled after C and C++ languages. it differs from C and C++ in many ways. Java
does not incorporate a number of features available in C and C++. For the benefit of C and C+ +
programmers, we point out here a few major differences between C+ + and Java languages.

Java and C

Java is a lot like C but the major difference between Java and C is Java is an object oriented
language and has mechanism to define classes and objects. In an effort to build a simple
and safe language, the Java learn did not include some of the C features in Java.
1. Java does not contain the data types struct and union
2. Java does not define the type modifiers keywords auto, extern. register, signed, and unsigned.
3. Java does not include the C unique statement keywords sizeof. and typcdef
4. Java does not support an explicit pointer type.
5. Java does not have a preprocessor and therefore we cannot use #define. # include, and # lfdef
statemenis
6. Java requires that functions with no arguments must be declared with empty parenthesis and
not with the void keyword as done in C.
7. Java adds labelled break and continue statements
Java and C++

1. Java adds new operators such as instanceof and >>>. IMP


2. Java does not support operator overloading.
3. Java does not have template classes as in C+4’
4. Java does not support multiple inheritance of classes. This is accomplished using a new
feature called Interface”.
5. Java does not support global variables. Every vanabic and method is declared within a class
and forms part of that class
6. Java has replaced the destructor function with a finalize( ) function
7. There arc no header files in Java.
8. Java does not use pointers.
Java and Internet
Java is strongly associated with the Internet because of the fact that the first application program
written in Java was HOT Java, a Web browser to run applets on Internet. Internet uses can use Java to
create applet programs and run them locally using Java enabled browse? such as Hot Java. They can
also use a Java-enabled browser to download an applet located on a computer anywhere in the
Internet and run it on his local computer. In fact, Java applet have made the Internet a true extension
of the storage system the local computer

Internet users can also set up their Web sites containing Java applets that could be used by other
remote users of Internet, The ability of Java applets to hitch a ride on the Information
Superhighway has madc Java a unique programming language for the Internet. In fact. due to this
java popularly known as Internet language.

Java and World Wide Web


World Wide Web (WWW) is an opcn-ended information retrieval system designed to be used in the
Internet’s distributed environment. This system contains what are known as Web pages that
provide both information and controls. Unlike a menu-driven system where we are guided through
a particular direction using a decision tree structure, the Web system is open-ended and we can
navigate to a new document in any direction. This is made possible with the help of a language
called hypertext Markup Language (HTML).
Web pages contain HTML tags that enable us to find, retrieve, manipulate and display documents
worldwide Java was meant to be used in distributed environments such as Internet. Since, both
the Web and Java share the same philosophy, Java could be easily incorporated into the Web
system. Before Java, the World Wide Web was limited to the display of still images and texts
However, the incorporation of Java into Web pages has made it capable of supporting animation,
graphics. games and a wide range of special effect,. With the support of Java, the Web has become
more interactive and dynamic. On the other hand, with the support of Web, we can run a Java program
on someone else’s computer across the Internet Java communicates with a Web page through a
special tag called <APPLET>.

User Computer Remote Computer

Byte Code APPLET SOURCE Code

Java web browser HTML Byte Code


Document

Applet Tag
Request

Output HTML document

Web Server
USERS

The figure shows the following communication steps:


1 The user sends a request for an HTML document to the remote computer’s Web server.
The Web server is program that accept a request. processes the request and sends the required
document.
2 The HTML document is returned to the user’s browser. The document contains the
APPI.F.T tag which identifies the applet.
3. The corresponding applet bytecode is transferred to the user’s computer. This bytecode had been
previously created by the Java compiler using the Java source code tile for that applet.
4 The Java-enabled browser on the user’s computer interprets the bytecode and provides output.
5. The user may have further interact with the applet but with no further downloading from the
provider’s Web server. This is because the byte code contains all necessary information to interpret
the applet .
Web Browsers
Internet is a vast sea of information represented in many formats and stored on many
computers. A large portion of the Internet is organized as the World Wide Web which uses
hypertext. Web browsers are used to navigate through the information found on the net They
allow us to retrieve the information spread across the Internet and display it using the
hypertext markup bnguiagc (HTML). Examples of Web browsers, among others, include:

1. Hot Java
2. Netscape Navigator
3. Internet Explorer

HotJava

HotJava is the Web browser from Sun Microsystems that enables the display of
interactive content on the Web, using the Java language. Hot Java is written entirely in
Java and demonstrates the capabilities of the Java programming language.

Netscape Navigator
Netscape Navigator is a general-purpose browser that can run Java appicts. With versions
available for Windows 95, NT, Solaris and Apple Macintosh. Netscape Navigator is one of
the most widely used browsers today.
Netscape Navigator has many usefull features such as visual display about downloading
process and indication of the numt’cr bytes downloaded. Ii also supports JavaScript, a
scripting language used in HTMl. document

Internet Explorer
Internet Explorer is another popi1ar browser developed by Microsoft for Windows 95, NT
and XI’ Workstations. Both the Navigator and Explorer use tool bars. icons, menus and dialog
boxes for easy navigation. Explorer uses a just-in-time (JIT) compiler which greatly increases
the speed of execution.
IMP
Hardware and Software Requirements
Java is currently supported on Windows 95. Windows NT, Windows XP, Sun Solaris.
Macintosh. and UNIX machines, Though, the programs and examples in this hook were tested
under Windows 95, the most popular operating system today, they can be implemented on
any of the above systems.

The minimum hardware and software requirements for Wmdows 95 version of Java are as
follows;
• IBM-compatible 486 system • A hard drive
• Minimum of 8 MB memory • A CD-ROM drive
• Windows 95 software • A Microsoft-compatible mouse
• A Windows-compatible sound card, if necessary
Java Support Systems
Java support systems consists of the following

Support Systems Description


Internet conne4ction Local computer should be connected to internet
Web server Program that accepts request for information and sends the required
documents
Web Browser Program that provides access to WWW and runs java applets
HTML A language for creating hypertext for web
Applet tag For placing java applets in html document
Java code Used for defining java applets
Byte code Compiled java code referred in APPLET tag
Java Environment IMP
Java environment includes a large number of development tools and hundreds of classes
and methods. The development tools arc part of the system known as Java Development Kit
(JDK) and the classes and methods are part of the Java Standard Library (JSL). also known as the
Application Programming Interface.(API).

1. Java Development Kit


The Java Development Kit comes with a collection of tools that are used for
developing and running Java program. They include
• appletviewcr (for viewing Java applets)
• javac (Java compiler)
• java (Java interpreter)
• javap (Java disassembler)
• javah (for C header files)
• javadoc (for creating HTML documents)
• jdb (Java debugger)

Below table lists these tools and description

JAVAC
javac is the compiler for the Java programming language; it's used to compile .java file. It
creates a class file which can be run by using java command.

EXAMPLE
c:\javac TestFile.java
JAVA

Application Programming Interface

The Java Standard Library (or API) includes hundreds of classes and methods grouped
into several functional package. Most commonly used packages arc:
Language Support Package: A collection of classes and methods required for
implementing basic features of Java.

1. Utilities Package: A collection of classes to provide utility functions such as date


and lime functions.
2. Input/ Output Package: A collection of classes required for input’output manipulation
3. Networklng Package: A collection of classes for communicating with other
computers via Internet.
4. AWT Package The Abstract Window Tool Kit packagc contains classes that
implements platform-independent graphical user interface
5. Applet Package: This includes a act of classes that allows us to create Java applets

Overview of Java Language


Introduction
Java ia a general-purpose, object-oriented programming language We can develop two types
of java programs:
• Stand-alone applications
• Web applets

1. Stand-alone applications arc programs written in Java to carry out certain tasks on a stand-
alone local computer. In fact. Java can be used to develop programs for all kinds of applications.
which earlier, were developed using languages like C and C++

Executing a stand-alone Java program involves two steps:


I. Compiling source code into byte codc using javac compiler
2. Executing the byte code program using java interpreter
Applets are small Java programs developed for internet applications. An applet Located
on a distant computer (Server) can be downloaded via Internet and executed on a local computer
(Client) using a Java-capable browser.

We can develop applets for doing everything from simple animated graphics to complex
games and utilities. Since applet’s are embedded in an HTML document and run inside a Web
page. creating and naming applets are more complex than creating an application.

They arc implemented as shown in below figure

JAVA
SOURCE
CODE

JAVA COMPILER

APPLET TYPE APPLICATION TYPE

JAVA ENABLED JAVA


WEB BROWSER INTERPRETER

OUTPUT OUTPUT

Simple Java Program


The best way to learn a new language is to write a few simple example
programs and execute them. We can begin with a very simple program that print a
line of text as output

Class SampleOne
{ public static void main (String args[])
{ System.out.println(“Java is Better than C.”):
}
}
Class Declaration
The first line class Samp1eOne declares a class, which as an object-oriented
construct. As stated earlier, Java is a true object-oriented language and therefore, every
thing must be placed inside a class, class is a keyword and declares that a new class
definition follows. SampleOne is a Java identifier that specifies the name of the class to be
defined
Opening Brace
Every class definition in Java begins with an opening brace { and cnd with a matching
closing brace “} appearing in the last line in the example.
“,

The Main Line is third line


public static void main (String args [])
defines a method named main. Conceptually. this is similar to the main( ) function
in C/C++. Every Java application program must include the main( ) method.. This is the
starting point for the interpreter to begin the execution of the program

The line contains keywords public, static, void

Public Public keyword is a access specifier that declares main method and
thereby making it accessible to all other classes
Static This keyword declares this method as one that belongs to entire class
and not a part of any object of the class
Void The type modifier void states that main method does not return any
value but prints some text to the scrren or performs calculations
JAVA PROGRAM STRUCTURE
Java program may coati many classes of which only one class defines a main method. Classes
contain data members and methods that operate on the data members of the class,
Methods may contain data type declarations and executable statements. To write a Java
program, we first define classes and then put them together. A Java program may contain one
or more sections as below.

Documentation section suggested


Package statement
optional
Import statement
Interface statement
Class declaration
Main method class
{ main method definition
Essential

}
Documentation Section
The documentation section comprises a set of comment lines giving the name of the program the
author and other details, which the programmer would like to refer to at a Later stage.
Comments must explain and greatly help in maintaining the program

Package Statement
This statement declares package name and informs the compiler that the classes
defined here belongs to this package.
Example : package student;

Import statement

is a new concept in java


Java Tokens
A Java program is basically a collection of classes A class is defined by a set of
declaration statements and mcthods contaning executable statements.

Most statements contain expressions. which describe the actions earned out on data. Smallest
individual units inaprogram are known as tokens. The compiler recognizes them for building
up expressions and statements.
Java language includes five types of tokens.

They are:
• Reserved Keywords
• Identifiers
• Literals
• Operators
• .Separators

Keywords
Keywords are essential parts of a language definition. Java language has reserved 50 words as
keywords. These keywords, combined with operators and separators according to syntax, form
definition of the Java language. Since keywords have specific meaning in Java, we cannot use them as
names for variables, classes, methods and so on All keywords arc to be written in lower-case letters.
Identifiers
Identifiers are programmer-designed tokens. They arc used for naming classes, methods,
variables. objects, labels, packages ans interfaces in a program.
Java identifiers follow the following rules.

I They can have alphabets, digits. and the underscore and dollar sign characters.
2. They must not begin with a digit.
3. Uppercase and lowercase letters are distinct,
4. They can be of any length.
Examples:
average
sum
Literals
Literals in Java are a scqucnce of characters digits. letters. and other characters that represent constant
values to be stored in variables. Java language specifies five major types of lilerals.
They are:
• Integer literals
• Floating point literals
• Character literals
• String literals
• Boolean literals

Each of them has a type associated with it. The type describes how thc values behave arid how they are
stored.
Operators
An operator is a symbol that takes one or more arguments and operates on them to produce a result.
Separators
Separators are symbols used to indicate where groups of code are divided and arranged,

Java Statements
The statements in Java are like sentences in natural languages. A statements is an executable
combination of tokens ending with a semicolon ( ; ) mark. Statements are usually executed in
sequence in the order in which they appear,
Java Virtual Machine
All language compilers translate source code into machine code for a specific computer. Java
compiler also does the same thing. Then, how does Java achieve architecture neutrality? The
answer is that the Java compiler produces an intermediate code known as bytecode for a
machine that does not exist. This machine is called the Java Virtual Machine and it
exists only inside the computer memory. it is a simulated computer within the computer
and does all major functions of a real computer. Below figure illustrates
the process of compiling a Java program into byte code which is also referred to as virtual machine
code

JAVA JAVA VIRTUAL


PROGRAM COMPILER MACHINE
SOURCE CODE BYTE CODE

PROCESS OF COMPILATION

The virtual machine code is not machine specific. The machine specific code (known as machine code)
is generated by the Java interpreter by acting as an intermediary between the virtual machine
and the real machine as shown in Fig. below
BYTE CODE JAVA MACHINE
INTEPRETER CODE
VIRTUAL MACHINE REAL MACHINE

PROCESS OF CONVERTING BYTE CODE INTO MACHINE CODE

Command Line Arguments


Command line arguments are parameters that are supplied to the application program at the time of
invoking it for execution. We can write Java programs that can receive and use the arguments provided
in the command line. e.g. public static void main (String args[]). args is declared as an array of strings
and arguments provided in the command line are passed to the array args as its elements.

Command line arguments are parameters that are supplied to the application program at the time of
invoking it for execution. We can write Java programs that can receive and use the arguments provided
in the command line. e.g. public static void main (String args[]). args is declared as an array of strings and
arguments provided in the command line are passed to the array args as its elements.

The user enters command-line arguments when invoking the application and specifies
them after the name of the class to be run. EXAMPLE java Echo JAVA IS EASY

Java displays as below


JAVA
IS
EASY
Constants, Variables, and Data Types
Introduction
A programming language is designed to process certain kinds of data consisting of numbers.
characters and strings and to provide useful outpw known as information, The task of
processing data is accomplishcd by exuting a sequence of instructions constituting a program.
These instructions are formed using certain symbols and words according to some rigid
rules known as syntax rules (or grammar).

Constants
Constants in Java refer to fixed values that do not change during the execution of a program.
Java supports several types of constants as illustrated in Fig. below

Integer Constants
An integer constant refers to a sequence of digits. Thcrc are three types of integers namely,
decimal integer. octal integer and hexa decimal integer.

Decimal integer consist of a set of digits. 0 through 9. preceded by an optional minus sign. Valid
examples of decimal integer constants are

123 -321 0 654321

Embedded spaces. commas, and non-digit characters arc not permitted between digits.

For example.
15 750 20.000 $1000 are illegal numbers

JAVA CONSTANTS

NUMERIC CONSTANT CHARACTER CONSTANT

INTEGER CONSTANT REAL CONSTANT CHARACTER CONSTANT STRING CONSTANT


An octal integer constant consists of any combination of digits from the set U through
1, with a leading 0.

Some examples of octal integer are: 037 0 0435 0551

A sequence of digits preceded by Ox or OX is considered as hexadecimal integer (hex


integer). They may also include alphabets A through F or a through f: A letter A
through F represents the numbers 10 through 15.

Following are the examples of valid hex integers. 0x2 OX9F Oxbcd Ox

BITWISE OPERATORS
Bitwise operators are operators that perform operations on data that are in the form of bits ir 0 and 1.

The Different bitwise operators in C are

1. BITWISE AND (&)


2. BITWISE OR (||)
3. BITWISE XOR (^)
4. BITWISE COMPLEMENT (~)
5. BITWISE LEFT SHIFT (<<)
6. BITWISE RIGHT SHIFT (>>)

Bitwise AND operator &


The output of bitwise AND is 1 if the corresponding bits of two operands is 1. If either bit of an
operand is 0, the result of corresponding bit is evaluated to 0.

Let us suppose the bitwise AND operation of two integers 12 and 25.

12 = 00001100 (In Binary)

25 = 00011001 (In Binary)

Bit Operation of 12 and 25

00001100
& 00011001

________

00001000 = 8 (In decimal)

Example #1: Bitwise AND

#include <stdio.h>
int main()
{
int a = 12, b = 25;
printf("Output = %d", a&b);
return 0;
}

Output

Output = 8

Bitwise OR operator |
The output of bitwise OR is 1 if at least one corresponding bit of two operands is 1. In C
Programming, bitwise OR operator is denoted by |.

12 = 00001100 (In Binary)

25 = 00011001 (In Binary)

Bitwise OR Operation of 12 and 25

00001100
| 00011001

________

00011101 = 29 (In decimal)

Example #2: Bitwise OR

#include <stdio.h>
int main()
{
int a = 12, b = 25;
printf("Output = %d", a|b);
return 0;
}

Output

Output = 29

Bitwise XOR (exclusive OR) operator


The result of bitwise XOR operator is 1 if the corresponding bits of two operands are opposite. It
is denoted by ^.

12 = 00001100 (In Binary)

25 = 00011001 (In Binary)

Bitwise XOR Operation of 12 and 25

00001100
^ 00011001

________

00010101 = 21 (In decimal)

Example #3: Bitwise XOR

#include <stdio.h>
int main()
{
int a = 12, b = 25;
printf("Output = %d", a^b);
return 0;
}

Output

Output = 21

Bitwise complement operator ~


Bitwise compliment operator is an unary operator (works on only one operand). It changes 1 to 0
and 0 to 1. It is denoted by ~.

35 = 00100011 (In Binary)

Bitwise complement Operation of 35

~ 00100011

________
11011100 = 220 (In decimal)

Twist in bitwise complement operator in C Programming


The bitwise complement of 35 (~35) is -36 instead of 220, but why?

For any integer n, bitwise complement of n will be -(n+1). To understand this, you should have
the knowledge of 2's complement.

2's Complement
Two's complement is an operation on binary numbers. The 2's complement of a number is equal
to the complement of that number plus 1. For example:

Decimal Binary 2's complement

0 00000000 -(11111111+1) = -00000000 = -0(decimal)


1 00000001 -(11111110+1) = -11111111 = -
256(decimal)
12 00001100 -(11110011+1) = -11110100 = -
244(decimal)
220 11011100 -(00100011+1) = -00100100 = -
36(decimal)

Note: Overflow is ignored while computing 2's complement.

The bitwise complement of 35 is 220 (in decimal). The 2's complement of 220 is -36. Hence, the
output is -36 instead of 220.

Bitwise complement of any number N is -(N+1). Here's how:


bitwise complement of N = ~N (represented in 2's complement form)
2'complement of ~N= -(~(~N)+1) = -(N+1)

Example #4: Bitwise complement


#include <stdio.h>
int main()
{
printf("Output = %d\n",~35);
printf("Output = %d\n",~-12);
return 0;
}
Output

Output = -36
Output = 11

Shift Operators in C programming

There are two shift operators in C programming:

 Right shift operator


 Left shift operator.

Right Shift Operator

Right shift operator shifts all bits towards right by certain number of specified bits. It is denoted
by >>.

212 = 11010100 (In binary)


212>>2 = 00110101 (In binary) [Right shift by two bits]
212>>7 = 00000001 (In binary)
212>>8 = 00000000
212>>0 = 11010100 (No Shift)

Left Shift Operator

Left shift operator shifts all bits towards left by certain number of specified bits. It is denoted by
<<.

212 = 11010100 (In binary)


212<<1 = 110101000 (In binary) [Left shift by one bit]
212<<0 =11010100 (Shift by 0)
212<<4 = 110101000000 (In binary) =3392(In decimal)

Example #5: Shift Operators


#include <stdio.h>
int main()
{
int num=212, i;
for (i=0; i<=2; ++i)
printf("Right shift by %d: %d\n", i, num>>i);

printf("\n");

for (i=0; i<=2; ++i)


printf("Left shift by %d: %d\n", i, num<<i);

return 0;
}

Right Shift by 0: 212


Right Shift by 1: 106
Right Shift by 2: 53

Left Shift by 0: 212


Left Shift by 1: 424
Left Shift by 2: 848

You might also like