core java_2

53
SHAHEED UDHAM SINGH COLLEGE OF ENGINEERING & TECHNOLOGY TANGORI (MOHALI) DEPARTMENT OF ELECTRONICS & COMMUNICATION INDUSTRIAL TRAINING CORE JAVA SUBMITTED TO: SUBMITTED BY: MANISH KUMAR ECE (eve) 1154677

Upload: sarthakyoungistan1

Post on 17-Dec-2015

7 views

Category:

Documents


1 download

DESCRIPTION

core java report

TRANSCRIPT

A REPORT ON

SHAHEED UDHAM SINGH COLLEGE

OF

ENGINEERING & TECHNOLOGY

TANGORI (MOHALI)DEPARTMENT OF ELECTRONICS & COMMUNICATION

INDUSTRIAL TRAINING

CORE JAVA

SUBMITTED TO: SUBMITTED BY:

MANISH KUMAR

ECE (eve)

1154677

ACKNOWLEDGEMENTI am grateful to SHAHEED UDHAM SINGH COLLEGE OF ENGINEERING & TECHNOLOGY for permitting me to undergo for a minor project for the development of an expert system. While developing this project, I have learnt a lot. This will be an un-forgetful experience. While developing this project, a lot of difficulties were faced by me. But it was the help of some special people that I have gained much confidence and developed the project quite well.

I would like to thank all the lecturers of IIHT (SOUTH EX) to co-ordinate with me and provide me the information needed to complete the analysis part of this project. I would like to thank everyone who in anyway helped me in this project.

CONTENTS

Overview of Java Data Types, Variables Operators

Control Statements

Introducing Classes

Inheritance

Packages and Interfaces

Exception Handling

Multithreaded Programming

Applets, CHAPTER 1INTRODUCTION TO JAVA

Java was conceived by Gosling, Patrick Naughton,Chris Warth, Ed Frank and Mike Sheridan at Sun Microsystem, INC. in 1991.This language was initially calledOAK but was renamed JAVA in 1995.

Java is an object-oriented programming language with a built-in application programming interface (API) that can handle graphics and user interfaces and that can be used to create applications or applets. Because of its rich set of API's, similar to Macintosh and Windows, and its platform independence, Java can also be thought of as a platform in itself. Java also has standard libraries for doing mathematics.

Much of the syntax of Java is the same as C and C++. One major difference is that Java does not have pointers. However, the biggest difference is that you must write object oriented code in Java. Procedural pieces of code can only be embedded in objects. In the following we assume that the reader has some familiarity with a programming language. In particular, some familiarity with the syntax of C/C++ is useful.

What is Java?

Java (with a capital J) is a high-level, third generation programming language, like C, Fortran, Smalltalk, Perl, and many others. You can use Java to write computer applications that crunch numbers, process words, play games, store data or do any of the thousands of other things computer software can do.

Compared to other programming languages, Java is most similar to C. However although Java shares much of C's syntax, it is not C. Knowing how to program in C or, better yet, C++, will certainly help you to learn Java more quickly, but you don't need to know C to learn Java. Unlike C++ Java is not a superset of C. A Java compiler won't compile C code, and most large C programs need to be changed substantially before they can become Java programs.

What's most special about Java in relation to other programming languages is that it lets you write special programs called applets that can be downloaded from the Internet and played safely within a web browser. Traditional computer programs have far too much access to your system to be downloaded and executed willy-nilly.

Features of The Java

1 Plateform independent 2 Compiled & interpitted

3 Object oriented

4 Small ,simple, familier

5 Architechture Neutral

6 Multithreaded

CHAPTER 2

Java is Object-Oriented

Object oriented programming is the catch phrase of computer programming in the 1990's. Although object oriented programming has been around in one form or another since the Simula language was invented in the 1960's, it's really begun to take hold in modern GUI environments like Windows, Motif and the Mac. In object-oriented programs data is represented by objects. Objects have two sections, fields (instance variables) and methods. Fields tell you what an object is. Methods tell you what an object does. These fields and methods are closely tied to the object's real world characteristics and behavior. When a program is run messages are passed back and forth between objects. When an object receives a message it responds accordingly as defined by its methods.

Object oriented programming is alleged to have a number of advantages including:

Simpler, easier to read programs

More efficient reuse of code

Faster time to market

More robust, error-free code

In practice object-oriented programs have been just as slow, expensive and buggy as traditional non-object-oriented programs. In large part this is because the most popular object-oriented language is C++. C++ is a complex, difficult language that shares all the obfuscation of C while sharing none of C's efficiencies. It is possible in practice to write clean, easy-to-read Java code. In C++ this is almost unheard of outside of programming textbooks. The Three OOP Principles

All object-oriented programming languages provide mechanisms that help you implement the object-oriented model. They are encapsulation, inheritance, and polymorphism.

Object oriented programming is alleged to have a number of advantages including:

Simpler, easier to read programs

More efficient reuse of code

Faster time to market

More robust, error-free code

Lets take a look at these concepts now.

1 Encapsulation

2 Inheritance

3 Polymorphism

Encapsulation

Encapsulation is the mechanism that binds together code and the data it manipulatesand keeps both safe from outside interference and misuse. One way to think about encapsulation is as a protective wrapper that prevents the code and data from being arbitrarily accessed by other code defined outside the wrapper. Access to the code and data inside the wrapper is tightly controlled through a well-defined interface. To relate this

to the real world, consider the automatic transmission on an automobile. It encapsulates hundreds of bits of information about your engine, such as how much you are accelerating, the pitch of the surface you are on, and the position of the shift lever. You, as the user, have only one method of affecting this complex encapsulation: by moving the gear-shift lever. You can't affect the transmission by using the turn signal or windshield wipers, for example. Thus, the gear-shift lever is a well-defined (indeed, unique) interface to the transmission. Further, what occurs inside the transmission does not affect objects outside the transmission. For example, shifting gears does not turn on the headlights!

Because an automatic transmission is encapsulated, dozens of car manufacturers can implement one in any way they please. However, from the driver's point of view, they all work the same. This same idea can be applied to programming. The power of encapsulated code is that everyone knows how to access it and thus can use it regardless of the implementation detailsand without fear of unexpected side effects.

Inheritance

Inheritance is the process by which one object acquires the properties of another object.

This is important because it supports the concept of hierarchical classification. As mentioned earlier, most knowledge is made manageable by hierarchical (that is, topdown) classifications. For example, a Golden Retriever is part of the classification dog, which in turn is part of the mammal class, which is under the larger class animal. Without the use of hierarchies, each object would need to define all of its characteristics explicitly.

However, by use of inheritance, an object need only define those qualities that make it unique within its class.

It can inherit its general attributes from its parent. Thus, it is the

inheritance mechanism that makes it possible for one object to be a specific instance of a more general case. Let's take a closer look at this process.

Most people naturally view the world as made up of objects that are related to each other in a hierarchical way, such as animals, mammals, and dogs. If you wanted to describe animals in an abstract way, you would say they have some attributes, such as size, intelligence, and type of skeletal system. Animals also have certain behavioral aspects;

they eat, breathe, and sleep. This description of attributes and behavior is the class definition for animals.If you wanted to describe a more specific class of animals, such as mammals, they would have more specific attributes, such as type of teeth, and mammary glands. This is known as a subclass of animals, where animals are referred to as mammals superclass.Since mammals are simply more precisely specified animals, they inherit all of the attributes from animals. A deeply inherited subclass inherits all of the attributes from each

of its ancestors in the class hierarchy.

Inheritance

Polymorphism

Polymorphism (from the Greek, meaning "many forms") is a feature that allows one interface to be used for a general class of actions. The specific action is determined by the exact nature of the situation. Consider a stack (which is a last-in, first-out list). You might have a program that requires three types of stacks. One stack is used for integer values, one for floating-point values, and one for characters. The algorithm that implements each stack is the same, even though the data being stored differs. In a non object-oriented language, you would be required to create three different sets of stack routines, with each set using different names. However, because ofpolymorphism, in Java you can specify a general set of stack routines that all share the same names.

More generally, the concept of polymorphism is often expressed by the phrase "one interface, multiple methods." This means that it is possible to design a generic interface to a group of related activities. This helps reduce complexity by allowing the same interface to be used to specify a general class of action. It is the compiler's job to select the specific action (that is, method) as it applies to each situation. You, the programmer,

do not need to make this selection manually. You need only remember and utilize thegeneral interface.

CHAPTER 3

DATA TYPES , VARIABLES , arraysJava defines eight primitive types of data: byte, short, int, long, char, float, double, and boolean.

Integers :This group includes byte, short, int, and long, which are for whole-valued

signed numbers.

Floating : This group includes float and double, which represent

numbers with fractional precision.

Characters : This group includes char, which represents symbols in a character set,

like letters and numbers.

Boolean : This group includes boolean, which is a special type for representing

true/false values.byte

The smallest integer type is byte. This is a signed 8-bit type that has a range from 128 to 127.

short

short is a signed 16-bit type. It has a range from 32,768 to 32,767

int

The most commonly used integer type is int. It is a signed 32-bit type that has a range from 2,147,483,648 to 2,147,483,647.

long

long is a signed 64-bit type and is useful for those occasions where an int type is not large enough to hold the desired value. The range of a long is quite large. This makes it useful when big, whole numbers are needed

float

The type float specifies a single-precision value that uses 32 bits of storage. Single precision is

faster on some processors and takes half as much space as double precision, but will become

imprecise when the values are either very large or very small. Variables of type float are useful

when you need a fractional component, but dont require a large degree of precision

double

Double precision, as denoted by the double keyword, uses 64 bits to store a value. Double precision is actually faster than single precision on some modern processors that have been optimized for high-speed mathematical calculations. All transcendental math functions, such as sin( ), cos( ), and sqrt( ), return double values.

Variables

The variable is the basic unit of storage in a Java program. A variable is defined by the

combination of an identifier, a type, and an optional initializer. In addition, all variables have

a scope, which defines their visibility, and a lifetime. These elements are examined next.

Declaring a Variable

In Java, all variables must be declared before they can be used. The basic form of a variable

Syntax :

type identifier [ = value][, identifier [= value] ...] ;

int a, b, c; // declares three ints, a, b, and c.

int d = 3, e, f = 5; // declares three more ints, initializing // d and f.

byte z = 22; // initializes z.

double pi = 3.14159; // declares an approximation of pi.

char x = 'x'; // the variable x has the value 'x'.

Dynamic Initialization

class DynInit {

public static void main(String args[]) {

double a = 3.0, b = 4.0;

// c is dynamically initialized

double c = Math.sqrt(a * a + b * b);

System.out.println("Hypotenuse is " + c);

}

}

Characters

In Java, the data type used to store characters is char. However, C/C++ programmers beware:

char in Java is not the same as char in C or C++. In C/C++, char is 8 bits wide. This is not the

case in Java. Instead, Java uses Unicode to represent characters. Unicode defines a fully

international character set that can represent all of the characters found in all human

languages. It is a unification of dozens of character sets, such as Latin, Greek, Arabic, Cyrillic,

Hebrew, Katakana, Hangul, and many more. For this purpose, it requires 16 bits. Thus, in

Java char is a 16-bit type. The range of a char is 0 to 65,536. There are no negative chars.

The standard set of characters known as ASCII still ranges from 0 to 127

class CharDemo {

public static void main(String args[]) {

char ch1, ch2;

ch1 = 88; // code for X

ch2 = 'Y';

System.out.print("ch1 and ch2: ");

System.out.println(ch1 + " " + ch2);

}

}Type Conversion and Casting

If the two types are compatible,

then Java will perform the conversion automatically. For example, it is always possible to

assign an int value to a long variable. However, not all types are compatible, and thus, not

all type conversions are implicitly allowed. For instance, there is no automatic conversion

defined from double to byte.

When one type of data is assigned to another type of variable, an automatic type conversion

will take place if the following two conditions are met:

The two types are compatible.

The destination type is larger than the source type.

To create a conversion between two incompatible types, you must use a cast. A cast is

simply an explicit type conversion. It has this general form:

(target-type) value

int a;

byte b;

b = (byte) a;

Arrays

An array is a group of like-typed variables that are referred to by a common name. Arrays of

any type can be created and may have one or more dimensions. Aspecific element in an array

is accessed by its index. Arrays offer a convenient means of grouping related information.

One-Dimensional Arrays

Aone-dimensional array is, essentially, a list of like-typed variables. To create an array, you first

must create an array variable of the desired type. The general form of a one-dimensional

array declaration is

type var-name[ ];

class num

{

public static void main (String[] args)

{

int[] num = new int{10,20,30,40,50};

for (int i=0;i> Shift right

>>> Shift right zero fill

>= Shift right assignment

>>>= Shift right zero fill assignment

= Greater than or equal to

100) c = d; // this if is

else a = c; // associated with this else

}

else a = d; // this else refers to if(i == 10)

The if-else-if Ladder

A common programming construct that is based upon a sequence of nested ifs is the

if-else-if ladder. It looks like this:

if(condition)

statement;

else if(condition)

statement;

else if(condition)

statement;

...

else

statement;

example :

class IfElse {

public static void main(String args[]) {

int month = 4; // April

String season;

if(month == 12 || month == 1 || month == 2)

season = "Winter";

else if(month == 3 || month == 4 || month == 5)

season = "Spring";

else if(month == 6 || month == 7 || month == 8)

season = "Summer";

else if(month == 9 || month == 10 || month == 11)

season = "Autumn";

else

season = "Bogus Month";

System.out.println("April is in the " + season + ".");

}

}

switch

The switch statement is Javas multiway branch statement. It provides an easy way to dispatch

execution to different parts of your code based on the value of an expression. As such, it often

provides a better alternative than a large series of if-else-if statements

import java.util.Scanner;

class weeks

{

public static void main (String[] args)

{

int num;

Scanner sc= new Scanner(System.in);

System.out.print("enter a number:");

num=sc.nextInt();

switch(num)

{

case 1:

System.out.print("Monday");

break;

case 2:

System.out.print("Tuesday");

break;

case 3:

System.out.print("Wednesday");

break;

case 4:

System.out.print("Thursday");

break;

case 5:

System.out.print("Friday");

break;

case 6:

System.out.print("Saturday");

break;

case 7:

System.out.print("Sunday");

break;

default:

System.out.print("invalid no.");

break;

}

}

}

Iteration Statements

Javas iteration statements are for, while, and do-while. These statements create what we

commonly call loops. As you probably know, a loop repeatedly executes the same set of

instructions until a termination condition is met. As you will see, Java has a loop to fit any

programming need.

while

The while loop is Javas most fundamental loop statement. It repeats a statement or block while its controlling expression is true.

Syntax:

while(condition) {

// body of loop

}import java.util.Scanner;

class odd

{

public static void main (String[] args)

{

int n,i=1;

Scanner sc= new Scanner(System.in);

System.out.print("enter a no.");

n=sc.nextInt();

while(i