core java basics

59
Core Java Basics www.harshithatechnologies.com [email protected] [email protected] 040-42020378, 9989630313 Software Training || Consulting || OutSourcing

Upload: mhtspvtltd

Post on 27-Jan-2017

400 views

Category:

Technology


1 download

TRANSCRIPT

Page 1: Core Java Basics

Core Java Basics

www.harshithatechnologies.cominfo@[email protected]

040-42020378, 9989630313

Software Training || Consulting || OutSourcing

Page 2: Core Java Basics

Data Types

Page 3: Core Java Basics

Data Types

Primitive Types

Type Representation Range

byte 8-bit, signed -128 to 127

short 16-bit, signed -32768 to 32767

int 32-bit, signed -2147483648 to 2147483647

long 64-bit, signed -9223372036854775808 to 9223372036854775807

char 16-bit, unsigned, Unicode

float 32-bit 1.40239846e-45 to 3.40282347e+38

double 64-bit 4.94065645841246544e-324 to 1.79769313486231570e+308

boolean

Page 4: Core Java Basics

Java Operators

Precedence Operator Description

1 ++, -- Increment and decrement

1 +, - Unary plus and minus

1 ~ Bitwise complement

1 ! Boolean

2 *, /, % Multiplication, division, remainder

3 +, - Addition and subtraction

3 + String

4 << Left shift

4 >> Right shift with sign extension

4 >>> Right shift with no extension

Page 5: Core Java Basics

5 <, <=, >, >= Numeric comparison

5 instanceof Type comparison

6 ==, != Equality and inequality of value

6 ==, != Equality and inequality of reference

7 & Bitwise AND

8 ^ Bitwise XOR

9 | Bitwise OR

10 && Conditional AND

11 || Conditional OR

12 ?: Conditional ternary operator

13 = *=, /=, %=, +=, -=, <<=, >>=, >>>=, &=, ^=, |=

Assignment

Page 6: Core Java Basics

Keywords

abstract default goto null synchronized

boolean do if package this

break double implements private throw

byte else import protected throws

case extends instanceof public transient

catch false int return true

char final interface short try

class finally long static void

const float native super volatile

continue for new switch while

Page 7: Core Java Basics

Comments

Java supports three styles of comments:

•A standard C-style comment, where all of the characters between

/* and */ are ignored.

•A single-line comment, where all of the characters from

// to the end of the line are ignored.

•A documentation comment that begins with

/** and ends with */.

Page 8: Core Java Basics

Literals

Integer literals

Integer literals can be specified in octal (base 8), decimal (base 10), or hexadecimal (base 16).

int i = 1230; int i = 01230; // i = 664 decimal int i = 0xFFFF; Floating-point literalsFloating-point literals are of type double unless they are suffixed with an f denoting that they are to be produced as a float value: double d = 8.31; double e = 3.00e+8; float f = 8.31F; float g = 3.00e+8F;

Page 9: Core Java Basics

Character literals

A literal character value can be specified either as a single-quoted character or as an escaped ASCII or Unicode sequence:

char a = 'a'; char newline = '\n'; char ch = 88 ; //code for XBoolean LiteralsIt can have only one of two possible values, true or falseboolean b = false;

Page 10: Core Java Basics

Type Conversion and Casting

When one type of data is assigned to another type of variable, an automatic type conversion will take place if

• The two types are compatible

• The destination type is larger than the source type.

Casting Incompatible Types

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

(target-type) value;

Page 11: Core Java Basics

Casting

1) int a;

a = 10;

byte b;

b = (byte) a;

2) byte b;

int i = 257;

b = (byte) i; // 1

3) double d = 223.22;

int i = (int) d; // 223

Page 12: Core Java Basics

Automatic Type Promotion in Expressions

Java automatically promotes each byte type or short operand to int when evaluating an expression.

byte b= 50;

b = b * 2; // Error. Cannot assign an int to a byte

b = (byte) (b*2); // valid

Page 13: Core Java Basics

Array Creation and Initialization

As in C, array indices start with zero.

After creation, the array elements are initialized to the default values for their type.

For numeric types, this means the elements are initially zero:

int [] grades = new int [30]; grades[0] = 99; grades[1] = 72;

Java supports the C-style curly braces {} construct for creating an array and initializing its elements when it is declared: int [] primes = { 1, 2, 3, 5, 7, 7+4 }; An array object of the proper type and length is implicitly created.

Page 14: Core Java Basics

Comparing C++ and JavaThe important features that distinguish Java from C++.1. The biggest potential stumbling block is speed:

interpreted Java runs in the range of 20 times slower than C.

2. Everything must be in a class. There are no global functions or global data. If you want the equivalent of globals, make static methods and static data within a class.

3. There are no structs or enumerations or unions, only classes.

4. All method definitions are defined in the body of the class. Thus, in C++ it would look like all the functions are inlined, but they’re not.

5. Class definitions are roughly the same form in Java as in C++, but there’s no closing semicolon. There are no class declarations of the form class foo; , only class definitions.

Page 15: Core Java Basics

6. There’s no scope resolution operator :: in Java. 7. In addition, package names are established using the dot, and to perform a kind of C++ #include you use the import keyword. For example: import java.awt.*;. 8. Java, like C++, has primitive types for efficient access. All the primitive types have specified sizes that are machine independent for portability. 9. Type-checking and type requirements are much tighter in Java. For example:

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

2. The result of an expression like X + Y must be used; 10. The char type uses the international 16-bit Unicode character set, so it can automatically represent most national characters.

Page 16: Core Java Basics

11. Static quoted strings are automatically converted into String objects. There is no independent static character array string like there is in C and C++.12. Java adds the triple right shift >>> to act as a “logical” right shift by inserting zeroes at the top end; 13. Although they look similar, arrays have a very different structure and behavior in Java than they do in C++. There’s a read-only length member that tells you how big the array is, and run-time checking throws an exception if you go out of bounds. All arrays are created on the heap, and you can assign one array to another (the array handle issimply copied). The array identifier is a an object14. All objects of non-primitive types can be created only via new. There’s no equivalent to creating non-primitive objects “on the stack” as in C++.

Page 17: Core Java Basics

15. All primitive types can be created only on the stack, without new. There are wrapper classes for all primitive classes so that you can create equivalent heap-based objects via new. 17. Java has no preprocessor. There are no preprocessor-like macros.18. Initialization of class data members is guaranteed in Java; if you don’t explicitly initialize them they get a default value (a zero or equivalent). You can initialize them explicitly, either when you define them in the class or in the constructor. 19. There are no Java pointers in the sense of C and C++.20. There are no destructors in Java. The lifetime of an object is determined instead by the garbage collector. There is a finalize( ) method that’s a member of each class, something like a C++ destructor, but finalize( ) is called by the garbage collector and is supposed to be responsible only for releasing "resources" (such as open files, sockets, ports, URLs, etc).

Page 18: Core Java Basics

21. Java does not support default arguments.22. Java uses a singly-rooted hierarchy, so all objects are ultimately inherited from the root class Object. In C++, you can start a new inheritance tree anywhere, so you end upwith a forest of trees. In Java you get a single ultimate hierarchy. 23. Garbage collection means memory leaks are much harder to cause in Java, but not impossible.24. No inline methods. The Java compiler might decide on its own to inline a method, but you don’t have much control over this. You can suggest inlining in Java by using the final keyword for a method.25. Java has method overloading, but no operator overloading.

Page 19: Core Java Basics

Generally, Java is more robust, via:– Object handles initialized to null (a keyword)– Handles are always checked and exceptions are thrown for failures– All array accesses are checked for bounds violations– Automatic garbage collection prevents memory leaks– Clean, relatively fool-proof exception handling– Simple language support for multithreading– Bytecode verification of network applets

Page 20: Core Java Basics

HelloWorld.javapublic class HelloWorld { public static void main(String[] args)

{ System.out.println("Hello World!");

} }

C:> javac HelloWorld.java //produces the HelloWorld.class

C:> java HelloWorld //when you invoke the interpreter, you do not supply the .class extension

Page 21: Core Java Basics

System class has several fields, and if you select

out you’ll discover that it’s a static PrintStream object.

Since it’s static you don’t need to create anything.

The out object is always there and you can just use it.

println( ), method prints to the console and end with a new line.

Page 22: Core Java Basics

class P

{

public static void main(String args[])

{ int x =34;

int y =42;

System.out.println("X = " + x);

System.out.println("y = " + y);

int z = x+y;

System.out.println("z = " + z);

}

}

All local variables has to be initialized before using.

Page 23: Core Java Basics

Arithmetic Operators and Logical Operators

are same as that of C Programming Language.

Page 24: Core Java Basics

The Left Shift operator

int i;

byte a = 256,b;

i = a<< 2;

b = (byte) (a<<2);

System.out.println(“ i and b : “ + i + “ “ + b);

// i and b : 256 and 0

a is promoted to int for the purpose of evaluation, left shifting the value 64 twice results in I containing the value 256

0100 0000

0000 0001 0000 0000

Page 25: Core Java Basics

The Right Shift operator

int a =32 ;

a = a >> 1; // a now contains 16

int x = 35;

x = x >> 2; // x contains 8

0010 0011 35

>>2

0000 1000 8

---------------------------------------------------

11111000 -8

>>1

11111100 -4

Page 26: Core Java Basics

The Unsigned Right Shift operator

>>> shifts zero’s into the high-order bit.

int a = -1 ;

a = a >>> 24;

11111111 11111111 11111111 11111111 // -1 in binary

>>> 24

00000000 00000000 00000000 11111111 // 255 in binary

Page 27: Core Java Basics

Boolean Logical Operators

& Logical AND

| Logical OR

^ Logical XOR

&& Short- Circuit Logical AND

|| Short- Circuit Logical OR

If you use the || and && forms rather than | and & forms , Java will not bother to evaluate the right hand operand when the outcome of the expression can be determined by the left operand alone.

if( denom != 0 && num /denom >10) // if denom =0 short circuit

if( c = =1 & e++ <100) d= 100;

Single & ensures that the increment operation will be applied whether c is equal to 1 or not.

Page 28: Core Java Basics

Classes and ObjectsA Class is a template for an object,

And an object is an instance of a class.

These characteristics represent a pure approach to object-oriented programming:

1. Everything is an object. 2. A program is a bunch of objects telling each

other what to do by sending messages. 3. All objects of a particular type can receive the

same messages. 4. Tight Cohesion within an object and Loose

coupling among objects.

Page 29: Core Java Basics

The Class of Circles

public class Circle { public double x, y; // The coordinates of the center public double r; // The radius // Method that returns the area of the circle

public double area( ) { return 3.14159 * r*r; }

}

Page 30: Core Java Basics

Objects Are Instances of a ClassWe can declare variables of that type: Circle c; But this variable c is simply a name that refers to a circle object; it is not an object itself. In Java, all objects must be created dynamically. This is almost always done with the new keyword: c = new Circle(); Now we have created an instance of our Circle class--a circle object--and have assigned it to the variable c, which is of type Circle. Accessing Object Datac.x = 2.0; // Initialize our circle to have center (2, 2) and radius 1.0. c.y = 2.0; c.r = 1.0;

Page 31: Core Java Basics

Using Object Methods

double a; a = c.area(); How can a method that takes no arguments know what data to operate on?

In fact, the area() method does have an argument! area() is implemented with an implicit argument

that is not shown in the method declaration. The implicit argument is named this, and refers to

"this object"-- the Circle object through which the method is invoked.

The implicit this argument is not shown in method signatures.

We can use the this keyword explicitly.

Page 32: Core Java Basics

Constructor

public class Circle { public double x, y, r; // The center and the radius of the circle // The constructor method. public Circle(double x, double y, double r) { this.x = x; this.y = y; this.r = r; } …………With this new constructor the initialization becomes part of the object creation step: Circle c = new Circle(1.414, -1.0,1 .25); There are two important notes about naming and declaring constructors:

•The constructor name is always the same as the class name. •The return type is implicitly an instance of the class.

Page 33: Core Java Basics

Multiple Circle Constructors

public class Circle { public double x, y, r; // Initializing constructorspublic Circle(double x, double y, double r) { this.x = x; this.y = y; this.r = r; }

public Circle(double r) { x = 0.0; y = 0.0; this.r = r; } // Copy Constructorpublic Circle(Circle c) { x = c.x; y = c.y; r = c.r; } //Default Constructorpublic Circle() { x = 0.0; y = 0.0; r = 1.0; }

Page 34: Core Java Basics

this Again

There is a specialized use of the this keyword that arises when a class has multiple constructors

--it can be used from a constructor to invoke one of the other constructors of the same class.

public Circle(double x, double y, double r) { this.x = x; this.y = y; this.r = r; } public Circle(double r) { this(0.0, 0.0, r); } public Circle(Circle c) { this(c.x, c.y, c.r); } public Circle() { this(0.0, 0.0, 1.0); }

This would be a more impressive example, of course, if the first constructor that we were invoking did a more significant amount of initialization.

Page 35: Core Java Basics

Class Variables

Java uses the static keyword to indicate that a particular variable is a class variable rather than an instance variable.

That is, that there is only one copy of the variable, associated with the class, rather than many copies of the variable associated with each instance of the class.

The one copy of the variable exists regardless of the number of instances of the class that are created--it exists and can be used even if the class is never actually instantiated.

Static Variable Example

public class Circle { static int num_circles = 0; // class variable: how many circles created public double x, y, r; // instance vars: the center and the radius public Circle(double x, double y, double r) { this.x = x; this.y = y; this.r = r; num_circles++; }

Page 36: Core Java Basics

Accessing Class Variables

Because static variables are associated with the class rather than with an instance, we access them through the class rather than through the instance

System.out.println("Number of circles created: " + Circle.num_circles);

Page 37: Core Java Basics

Constants: Another Class Variable Example

When computing the area and circumference of circles, we use the value pi. Since we use the value frequently, we don't want to keep typing out 3.14159, so we'll define it as a class variable that has a convenient name:

public class Circle { public static final double PI = 3.14159; public double x, y, r; // ... etc.... } Besides the static keyword that we've already seen, we use the final keyword, which means that this variable can never have its value changed.

Page 38: Core Java Basics

static Methods

Class methods are like class variables in a number of ways:

•Class methods are declared with the static keyword.

•Class methods are invoked through the class rather than through an instance.

•Class methods are the closest Java comes to "global" methods. Because they must be referred to by the class name, there is no danger of name conflicts.

•Class methods differ from instance methods in one important way: they are not passed an implicit this reference.

Page 39: Core Java Basics

A Class Method and an Instance Method

public class Circle { public double x, y, r; // An instance method. Returns the bigger of two circles. public Circle bigger(Circle c) { if (c.r > r) return c;

else return this; } // A class method. Returns the bigger of two circles. public static Circle bigger(Circle a, Circle b) { if (a.r > b.r) return a;

else return b; }

Page 40: Core Java Basics

. . // Other methods omitted here. . }

You would invoke the instance method like this:

Circle a = new Circle(2.0); Circle b = new Circle(3.0); Circle c = a.bigger(b); // or, b.bigger(a);

And you would invoke the class method like this:

Circle c = Circle.bigger(a,b);

Page 41: Core Java Basics

Object Destruction

How do you destroy objects when they are no longer needed?

The answer is: You don't!

Garbage Collection

The technique Java uses to get rid of objects once they are no longer needed is called garbage collection.

The Java interpreter knows what objects it has allocated.

It can figure out when an allocated object is no longer referred to by any other object or variable. When it finds such an object, it knows that it can destroy it safely, and does so.

The Java garbage collector runs as a low-priority thread, and does most of its work when nothing else is going on.

The only time the garbage collector must run while something high-priority is going on is when the interpreter has run out of memory.

Page 42: Core Java Basics

Object Finalization

Just as a constructor method performs initialization for an object, a Java finalizer method performs finalization for an object.

Garbage collection automatically frees up the memory resources used by objects.

But objects may hold other kinds of resources, such as file descriptors or sockets, as well.

The garbage collector can't free these resources up for you, so you should write a finalizer method that takes care of things like closing open files, terminating network connections, and so on.

Page 43: Core Java Basics

A finalizer is an instance method (i.e., non-static),

takes no arguments, returns no value (i.e., void), and must be named finalize().

Ex:

protected void finalize() throws IOException {

……}

Page 44: Core Java Basics

There are some additional things to be aware of about finalizers:

•If an object has a finalizer, that method is invoked before the system garbage collects the object.

•The Java interpreter may exit without garbage collecting all outstanding objects, so some finalizers may never be invoked. In this case, though, any outstanding resources are usually freed by the operating system.

•Java makes no guarantees about when garbage collection will occur, or what order objects will be collected in.

Page 45: Core Java Basics

Java access specifiersThe Java access specifiers public, protected and private are placed in front of each definition for each member in your class, whether it’s a data member or a method. Each access specifier controls the access for only that particular definition.“Friendly”The default access has no keyword, but it is commonly referred to as “friendly.” It means that all the other classes in the current package have access to the friendly member, but to all the classes outside of this package the member appears to be private. Since a compilation unit – a file – can belong only to a single package, all the classes within a single compilation unit are automatically friendly with each other.

Page 46: Core Java Basics

public: When you use the public keyword, it means that the member declaration that immediately follows public is available to everyone,private: The private keyword that means no one can access that member except that particular class, inside methods of that class.protected: “sort of friendly”Can be accessed from subclass in different package

A class cannot be private or protected. So you have only two choices for class access: “friendly” or public.

Page 47: Core Java Basics

Class Member Accessibility

Accessible to: public protected package private

Same class yes yes yes yes

subClass in same yes yes yes no

package

Subclass in yes yes no no

different package

Non-subclass,

different package yes no no no

Page 48: Core Java Basics

Examples on

Objects as arguments

Object Reference

String & StringBuffer class

Page 49: Core Java Basics

Inheritance : Extending a Class

class A

{ int i; }

class B extends A // B is a subclass of A

{ int j; }

class I1{

public static void main(String args[])

{ B ob = new B();

ob.i=10;

ob.j=20;

System.out.println("ob's value =" + ob.i +"," + ob.j);

}}

Page 50: Core Java Basics

class Rect { private int w,h;

void set(int x,int y)

{ w=x; h=y;

}

int area()

{ return w*h; }

void disp()

{

System.out.println("Width =" +w +", Height = " + h + "Area =" +area());

}

}

Example 2

Page 51: Core Java Basics

class Box extends Rect {

int d;

void set(int x,int y,int z)

{ set(x,y);

d=z;

}

void put()

{ disp();

System.out.println("Depth =" + d);

}

}

Page 52: Core Java Basics

class I3

{

public static void main(String args[])

{

Box ob = new Box();

ob.set(10,20,15);

ob.put();

}

}

Page 53: Core Java Basics

Constructor Chaining

class A { int i; public A() { // Implicit call to super(); here. i = 3; } } class B extends A { // Default constructor: public B() { super(); } }

Page 54: Core Java Basics

More on super …

Page 55: Core Java Basics

Shadowed Variables

class A { int x=10; }

class B extends A { int x=20; }

class C extends B { int x=30;

void disp()

{ // Variable x in class C.

System.out.println("x in C is :" + x);

// Variable x in class B.

System.out.println("x in B is :" + super.x);

System.out.println("x in B is :" + ((B)this).x);

// Variable x in class A.

System.out.println("x in A is :" + ((A)this).x);

}

Page 56: Core Java Basics

public static void main(String args[])

{

C obj = new C();

obj.disp();

}

}

Page 57: Core Java Basics

Overriding Is Not Shadowing

Method overriding is not like variable shadowing at all:

You can refer to shadowed variables simply by casting an object to the appropriate type.

You cannot invoke overridden methods with this technique.

Method Overriding versus Variable Shadowing

class A { int i = 1; int f() { return i; } }

Page 58: Core Java Basics

class B extends A { int i = 2; // Shadows variable i in class A. int f() { return -i; } // Overrides method f in class A. } public class override_test { public static void main(String args[]) {

B b = new B(); System.out.println(b.i); // Refers to B.i; prints 2. System.out.println(b.f()); // Refers to B.f(); prints -2. A a = (A) b; // Cast b to an instance of class A. System.out.println(a.i); // Now refers to A.i; prints 1; System.out.println(a.f()); // Still refers to B.f(); prints

-2; } }

Page 59: Core Java Basics

Core Java Basics

www.harshithatechnologies.cominfo@[email protected]

040-42020378, 9989630313

Software Training || Consulting || OutSourcing