Java Basics

37
Basic JAVA Write once run any where

description

my first kt. given in honing solution on basic java.

Transcript of Java Basics

Page 1: Java Basics

Basic JAVAWrite once run any where

Page 2: Java Basics

Basic Language Elements

Identifiers, Keywords, Literals, White Spaces and Comments

Identifiers

A name in a program is called an identifier.

An identifier in java is composed of a sequence of characters, where each character can be either a letter or digit or connecting symbol($,_).

The first character in an identifier can’t be a digit.

Identifiers in java are case sensitive.

Keywords

Key words are reserved identifiers.

In java, all keywords are in lower case.

Literals

A literal denotes a constant value of a particular data type, the value a literal represents remains unchanged in the program.

Page 3: Java Basics

Primitive Data Types

DataType Bit Depth

1. boolean jvm specific

2. byte 8 bits

3. short 16 bits

4. int 32 bits

5. long 64 bits

6. char 16 bits

7. float 32 bits

8. double 64 bits

All numeric data types except char are signed data types.

The default data type of an integer (byte, short, int, long) literal is always int.

long can be specified by appending L or l as a suffix.There’s no way to represent a byte or short literal.

The dafault data type of floating point literal is double.

float can be specified by appending F or f as a suffix.

Page 4: Java Basics

Java’s Keywords

boolean byte char short int long float double

public private protected abstract static final native synchronized

transient volatile strictfp if else do while for

switch case default break continue assert class interface

extends implements import package new instanceof super this

try catch finally throw throws void return enum

Java’s Reserved words

const goto

Java’s reserved Literals

true false null

ХJava doesn’t allow us to use any of the above as an identifier.

Q] /* // */ is it legal ?

Q] which of the following are keywords in java ?

a) instaceof b) object c) void d) main e) String f) enum g) null h) thrown

i)finalize j) native

Page 5: Java Basics

Java Source file structure

» An optional package declaration

» Zero or more import declarations

» Any no.of top level classes and interface declarations

At the most one public class definition per source class can be defined.

If a public class is defined, the file name must match this class name.

Except for package and import statements, all code is encapsulated in classes and interfaces.

like any other method, the main method can also be overloaded and overrided.

Q] which of the following are valid main() method declarations in order to start the execution of java application ?

a) Public static void main(String args) throws Exception

b) static public void main(String[] args)

c) final public static void main(String args[])

Page 6: Java Basics

Class (a user defined data type)

class is a logical construct upon which the entire java language is built.

Objects are basic run time entities in java. class acts as a blue print for similar type of objects.

when you design a class, think about the objects that will be created from that class, think about

1. Things the object knows (state)

2. Things the object does (behavior)

Alarm

alarmTime

setAlarmTime()getAlarmTime()isAlarmSet()

Things an object knows itself are called instance variables. Things an object can do are called methods.

classes give modularity in java.

Page 7: Java Basics

[class modifiers] class <class name> [extends clause] [implements clause]

{

[variable declarations]

[method declarations]

[constructor declarations]

[initializer blocks]

[nested class declarations]

[nested interface declarations]

}

class Syntax

Page 8: Java Basics

Java Variables

A variable stores a value of a particular type.

in java variables come in two flavors

1. primitive

2. reference

Variables that store references to objects are called reference variables.

java has three types of variables

1. instance variables

2. static variables

3. local variables

Page 9: Java Basics

Instance variables» Every object of the class will have its own copies of these variables, which are local to object» The values of these variables at any given time constitute the state of the object» Instance variables exist as long as object they belong to exist

Static variables

» Belong only to the class, but not created for only object of the class

» All objects of the class share the same copy of this variable

» Class variables exist as long as class exist

Local Variables

» Variables declared in methods including parameters or blocks are called Local variables

» After execution of the method or block completes local variables are no longer accessible

Page 10: Java Basics

Local variables must be explicitly initialized before being used. The compiler will report attempt to use un initialized local variables.

if no initialization is provided for static or instance variable they are initialized by default value of their type.

Default values of static/instance variables

Data Type Default Value

boolean false

char ‘\u0000’

int or short or byte 0

long 0L

float 0.0f

double 0.0

reference types null

Page 11: Java Basics

Java operators

() [] .

++ -- ~ !

* / %

+ -

<< >> >>>

>= < <=

== !=

&

^

|

&&

||

?:

= op=

Precedence table

Precedence rules are used to determine which operator should be applied first if there are two operators with different precedence.

The associative rules are used to determine which operator should be applied first if there are more than one operand with the same precedence.

the precedence and associative rules together determine the evolution order of operators in an expression.

All binary operators, except for the assignment operator associate from left to right

Except for unary postfix increment and decrement operators, all unary operators, all assignment operator and ternary conditional operator associate from right to left.

Page 12: Java Basics

new operator is used to create objects and declare array sizes.

instanceof operator is used to test an object’s type.

<source reference type> instanceof <destination type>

Q] int x=3;

x<<4;

s.o.p(x);

Q] int i=--4*2--;

s.o.p(i);

Page 13: Java Basics

Type Conversions

Java being a strongly typed language , checks for compatibility at compile time. How ever some checks are only possible at runtime.

Java demands that a cast be used to explicitly indicate the type conversion (narrowing or downcasting)

(<type>) expression;

Casting the value of a super class reference to a subclass type is downcasting and the reverse is called upcasting.

Casting between primitive types and reference types is not possible

Boolean values can’t be cast to other data types and vice versa

Widening and upcasting are implicit conversions

Narrowing typically requires explicit casting.

widening

byte short char int long float double

Page 14: Java Basics

Numeric promotions

Numeric promotion is implicitly applied on the operands to convert them to permissible types.

Unary numeric promotion

if the single operand of the operator has a type narrower than int, it is converted to int by an implicit widening primitive conversion;

Binary numeric promotion

Given T to be the broadest numeric type of two operands the operands are promoted as follows

If( T is broader than int)

both operands are converted to T

else

both operands are converted to int

Page 15: Java Basics

Implicit narrowing conversions

implicit narrowing conversions on assignment can occur in cases where all of the following conditions are full filled

1. The source is a constant expression of either byte, short, char, or int type

2. The destination type is either byte, short or char type

3. The value of the source is determined to be in the range of the destination type at compile time

Type conversion contexts

Assignments

Method invocation involving parameters

Arithmetic expression involving numeric types

String Concatenation involving String objects and other data types

Q] byte b=17;

b=b+2; //illegal

b+=2; //legal

Page 16: Java Basics

Arrays In java, arrays are objects

Array declaration

<element type>[] <array name>

(or)

<element type> <array name>[]

<array name> =new <element type>[size];

when the array is constructed, all its elements are initialized to the default value of their element type. This is true for both members and local arrays.

Java supports declaring , constructing, and explicitly initializing an array in one stmt.

eg: int[] a={4,3,78,3};

Anonymous array

new <element type>[] {array list}

eg:new int[] {4,7,3,8,9};

Multi dimensional arrays

Page 17: Java Basics

Method

[method modifiers] <return type> <method name> ([formal parameters]) [throws clause]

{

[local variable declarations]

[statements]

[nested class declarations]

}

Parameter passing

The parameter strategy in java is pass-by-value regardless of the type of the parameter.

The order of the evolution in actual parameter list is always from left to right.

if the actual parameter is a reference to an object then the reference value is passed and not the object itself.

Page 18: Java Basics

Method Over Loading

Several methods may have the same name, as long as the method signatures differ.

For the over loading method,

The arguments list must be different

The return types can be different

You can vary access levels in any direction

<There’s no polymorphism with over loading methods>

Page 19: Java Basics

Method Overriding

For the overriding method ,

Signature must be same as original method.

Return type must be compatible with original method return type

The new method definition can’t narrow the accessibility

The new method definition can only specify all or none or a subset of exception classes in the throws clause.

An instance method in a sub class can’t override a static method in the super class and vice versa.

We can’t override static methods rather we can hide them

Page 20: Java Basics

Interfaces

[access modifier] interface <interface name> <extends interface clause>

{

[constant declarations]

[method prototype declarations]

}

The methods in an interface are implicitly abstract and public and the constants are implicitly public, static and final.

An interface can extend other interfaces

An interface which has no methods to implement is known as Marker or tag or ability interface.

Page 21: Java Basics

Inheritance

It allows new classes to be derived from existing classes. And it is the main thing in Java for code reuse.

private members of a class are not inherited and also members that have a package accessibility in the super class are also not inherited by sub classes in other packages.

Since constructors and initializer blocks are not members of a class they are not inherited by a sub class.

To avoid D3(Deadly Diamond of Death) problem java doesn’t support multiple inheritance. So a class in java can extend at most one other class.

java gives multiple interface inheritance through interfaces. So a class can implement many interfaces.

Any class that doesn’t explicitly extend another class, implicitly extends <Object> class.

So any class in java, either directly or indirectly extends Object class.

Page 22: Java Basics

classes up the inheritance hierarchy are more generalized and classes down the hierarchy are more specialized.

Inheritance defines the is-a relationship between a super class and its sub class. This means that an object of a sub class can be used where ever an object of the super class can be used.

It is not possible for two classes to be the super classes of each other

If A extends B then A is-a B

Aggregation

Aggregation defines has-a relationship between objects.

If A has a reference to B then A has-a B

Page 23: Java Basics

Polymorphism

The ability of a super class or super type reference to denote objects of its own class and its sub classes at runtime is called polymorphism.

polymorphism is achieved through inheritance and interface implementation

The instance method invocation is dependent on the type of the actual object denoted by the reference at runtime.

Field access and static method access is determined by the reference type not by the actual object.

you can call a method on an object only if the class of the reference variable has that method.

Page 24: Java Basics

Static Block

static

{

//code

}

The code in a static block is executed once only when the class is loaded .

These are primarily used for initializing static fields.

Static block is not contained in any method

A class can have more than one static block. In this case the blocks are executed in the order of their declarations in the class.

Page 25: Java Basics

Instance Block

{

//code

}

The code in an instance block is executed every time an object is created.

Instance block is not contained in any method

A class can have more than one instance block. In this the blocks are executed in the order of their declarations in the class.

An instance initializer block can be used to factor out common initialization code that will be executed regardless of which constructor is invoked.

Page 26: Java Basics

Control Flow stmts

Control flow statements govern the flow of control in a program during execution.

There are three categories of control flow stmts

1. Selection stmts [if, if-else, switch]

2. Iteration stmts [for, while, do-while]

3. Transfer stmts [break, continue, return, throw, try-catch-flow and assert]

Page 27: Java Basics

Packages

A package in java is an encapsulation mechanism that can be used to group related classes, interfaces and sub packages.

package <fully qualified package name>

At most one package declaration can appear in a source file, and it must be the first statement.

The package name is saved in java byte code for the types contained in the package.

If a package stmt is omitted in a source file, then respective class files are placed in a unnamed package (current working directory)

packages prevent class name conflicts.

(java convention) preface your packages with your reverse domain name to prevent package name conflicts.

To put your class in package, The package hierarchy must match the directory structure

Page 28: Java Basics

Using packages,

we can use the existing package in two ways

1. Using the fully qualified name of the type.

2. Using import declarations.

Import

import <fully qualified name> // single type import

import <fully qualified name>.* //import on demand

An import declaration doesn’t recursively import sub packages.

Page 29: Java Basics

Modifiers

1. Access modifiers

public

protected

no modifier (package access)

private

2. static

3. final

4. abstract

5. synchronized

6. native

7. transient

8. volatile

9. threadsafe

Page 30: Java Basics

Top level classes and interfaces

public, no modifier

abstract and final

Inner classes All Access modifiers

abstract, static and final

Fields All access modifiers

static, final, transient and volatile

Methods All access modifiers

abstract, static, final, synchronized and native

Member Type Possible modifiers

Page 31: Java Basics

Modifier Class Package Sub class

(out side package)

World

public Y Y Y Y

protected Y Y Y N

default Y Y N N

private Y N N N

Access modifiers

Use most restrictive access level that makes sense for a particular member.

Avoid public fields accept for constants

public fields limit your flexibility in changing your code.

Page 32: Java Basics

Abstract method

An abstract method has no implementation (no body) it just specifies method prototype

You can’t have an abstract method in a non abstract class

If you put even a single abstract method in a class, you have to make the class abstract.

Only an instance method can be declared as abstract (we can’t override a static method)

A final method can’t be abstract

Page 33: Java Basics

Abstract class

Abstract class means, The class which is partially implemented

We can’t instantiate an abstract class. We can still use the abstract type as a reference type, for the purpose of polymorphism

If you put even a single abstract method in a class you have to make the class abstract.

Even if there are no abstract methods you can declare class as abstract just make it as a non concrete class.

You can mix both abstract and non-abstract methods in an abstract class.

The sub class which extends abstract class must implement all the abstract methods or declare it also as abstract.

Page 34: Java Basics

static

Static members belong to the class in which they are declared.

We can access static members through class name or through object reference of that class.

We can’t access non-static members in static context.

Static context =>static initializer expression

static initializer blocks

static methods

static inner classes

Object needn’t be instantiated to access its static members.

Only inner classes can be declared as static

static variables are not part of a object state

we can’t override static methods in sub classes, rather we can hide them

Page 35: Java Basics

Final variable

A final variable of primitive data type can’t change its value once it has been initialized

A final variable of a reference type can’t change its reference value once it has been initialized but the state of the object it denotes can still be changed.

Applicable to instance, static, and local variables.

Blank finals

Final method

We can’t override a final method in sub classes.

Final class

A Final class can’t be extended

only a class whose definition is complete can be declared final.

Page 36: Java Basics

Make a class that doesn’t extends any thing when your new classes doesn’t passes is-a test for any other type.

Make a sub class only when you need to make a more specific version of a class and need to override or add new behavior

Use an abstract class when you want to define a template for a group classes and at least you have some implementation that all classes could use.

Use an interface when you want to define a role that other classes can play regardless of where those classes are in the inheritance tree.

Page 37: Java Basics

This was my first KT. Given in honing solutions in 2006.