SlideShare ist ein Scribd-Unternehmen logo
1 von 37
Basic JAVA
Write once run any where
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.
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.
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
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[])
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.
[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
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
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
 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
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.
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);
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
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
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
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
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.
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>
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
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.
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.
 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
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.
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.
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.
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]
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
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.
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
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
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.
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
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.
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
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.
 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.
This was my first KT.
Given in honing solutions in 2006.

Weitere ähnliche Inhalte

Was ist angesagt?

Core Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsCore Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsMahika Tutorials
 
Oops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in JavaOops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in JavaMadishetty Prathibha
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaCPD INDIA
 
Java Presentation
Java PresentationJava Presentation
Java Presentationpm2214
 
20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental Principles20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental PrinciplesIntro C# Book
 
C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#Hawkman Academy
 
Presentation on Visual Studio
Presentation on Visual StudioPresentation on Visual Studio
Presentation on Visual StudioMuhammad Aqeel
 
Java - Generic programming
Java - Generic programmingJava - Generic programming
Java - Generic programmingRiccardo Cardin
 
Introduction to java
Introduction to java Introduction to java
Introduction to java Sandeep Rawat
 
Core java concepts
Core java  conceptsCore java  concepts
Core java conceptsRam132
 

Was ist angesagt? (20)

Core Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsCore Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika Tutorials
 
Generics
GenericsGenerics
Generics
 
Oops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in JavaOops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in Java
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
 
Java Presentation
Java PresentationJava Presentation
Java Presentation
 
20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental Principles20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental Principles
 
C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#
 
Presentation on Visual Studio
Presentation on Visual StudioPresentation on Visual Studio
Presentation on Visual Studio
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
Java - Generic programming
Java - Generic programmingJava - Generic programming
Java - Generic programming
 
Introduction to java
Introduction to java Introduction to java
Introduction to java
 
History of java'
History of java'History of java'
History of java'
 
Gradle Introduction
Gradle IntroductionGradle Introduction
Gradle Introduction
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Final keyword in java
Final keyword in javaFinal keyword in java
Final keyword in java
 
Introduction to gradle
Introduction to gradleIntroduction to gradle
Introduction to gradle
 
Maven Introduction
Maven IntroductionMaven Introduction
Maven Introduction
 
Coding standard
Coding standardCoding standard
Coding standard
 
Generics in java
Generics in javaGenerics in java
Generics in java
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
 

Andere mochten auch

Java session01
Java session01Java session01
Java session01Niit Care
 
Chapter 1 introduction to java technology
Chapter 1 introduction to java technologyChapter 1 introduction to java technology
Chapter 1 introduction to java technologysshhzap
 
Jena – A Semantic Web Framework for Java
Jena – A Semantic Web Framework for JavaJena – A Semantic Web Framework for Java
Jena – A Semantic Web Framework for JavaAleksander Pohl
 
Intuit commissions manager
Intuit commissions managerIntuit commissions manager
Intuit commissions managersshhzap
 
Chapter 1. java programming language overview
Chapter 1. java programming language overviewChapter 1. java programming language overview
Chapter 1. java programming language overviewJong Soon Bok
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with JavaJussi Pohjolainen
 
Object-Oriented Analysis And Design With Applications Grady Booch
Object-Oriented Analysis And Design With Applications Grady BoochObject-Oriented Analysis And Design With Applications Grady Booch
Object-Oriented Analysis And Design With Applications Grady BoochSorina Chirilă
 

Andere mochten auch (9)

Java session01
Java session01Java session01
Java session01
 
Chapter 1 introduction to java technology
Chapter 1 introduction to java technologyChapter 1 introduction to java technology
Chapter 1 introduction to java technology
 
Introduction to java technology
Introduction to java technologyIntroduction to java technology
Introduction to java technology
 
Jena – A Semantic Web Framework for Java
Jena – A Semantic Web Framework for JavaJena – A Semantic Web Framework for Java
Jena – A Semantic Web Framework for Java
 
Intuit commissions manager
Intuit commissions managerIntuit commissions manager
Intuit commissions manager
 
Chapter 1. java programming language overview
Chapter 1. java programming language overviewChapter 1. java programming language overview
Chapter 1. java programming language overview
 
02 basic java programming and operators
02 basic java programming and operators02 basic java programming and operators
02 basic java programming and operators
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
 
Object-Oriented Analysis And Design With Applications Grady Booch
Object-Oriented Analysis And Design With Applications Grady BoochObject-Oriented Analysis And Design With Applications Grady Booch
Object-Oriented Analysis And Design With Applications Grady Booch
 

Ähnlich wie Java Basics

Learning core java
Learning core javaLearning core java
Learning core javaAbhay Bharti
 
Lecture2_MCS4_Evening.pptx
Lecture2_MCS4_Evening.pptxLecture2_MCS4_Evening.pptx
Lecture2_MCS4_Evening.pptxSaqlainYaqub1
 
Lecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops conceptLecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops conceptmanish kumar
 
Fundamental programming structures in java
Fundamental programming structures in javaFundamental programming structures in java
Fundamental programming structures in javaShashwat Shriparv
 
C# language basics (Visual Studio)
C# language basics (Visual Studio) C# language basics (Visual Studio)
C# language basics (Visual Studio) rnkhan
 
C# language basics (Visual studio)
C# language basics (Visual studio)C# language basics (Visual studio)
C# language basics (Visual studio)rnkhan
 
java Basic Programming Needs
java Basic Programming Needsjava Basic Programming Needs
java Basic Programming NeedsRaja Sekhar
 
Chapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B KuteChapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B KuteTushar B Kute
 
Data Types, Variables, and Operators
Data Types, Variables, and OperatorsData Types, Variables, and Operators
Data Types, Variables, and OperatorsMarwa Ali Eissa
 
Java data types, variables and jvm
Java data types, variables and jvm Java data types, variables and jvm
Java data types, variables and jvm Madishetty Prathibha
 
Android Training (Java Review)
Android Training (Java Review)Android Training (Java Review)
Android Training (Java Review)Khaled Anaqwa
 

Ähnlich wie Java Basics (20)

Md03 - part3
Md03 - part3Md03 - part3
Md03 - part3
 
Learning core java
Learning core javaLearning core java
Learning core java
 
Lecture2_MCS4_Evening.pptx
Lecture2_MCS4_Evening.pptxLecture2_MCS4_Evening.pptx
Lecture2_MCS4_Evening.pptx
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
 
Lecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops conceptLecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops concept
 
Java Basics
Java BasicsJava Basics
Java Basics
 
PCSTt11 overview of java
PCSTt11 overview of javaPCSTt11 overview of java
PCSTt11 overview of java
 
Java Programming
Java Programming Java Programming
Java Programming
 
Introduction to-programming
Introduction to-programmingIntroduction to-programming
Introduction to-programming
 
Fundamental programming structures in java
Fundamental programming structures in javaFundamental programming structures in java
Fundamental programming structures in java
 
C# language basics (Visual Studio)
C# language basics (Visual Studio) C# language basics (Visual Studio)
C# language basics (Visual Studio)
 
C# language basics (Visual studio)
C# language basics (Visual studio)C# language basics (Visual studio)
C# language basics (Visual studio)
 
java Basic Programming Needs
java Basic Programming Needsjava Basic Programming Needs
java Basic Programming Needs
 
Chapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B KuteChapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B Kute
 
Basic
BasicBasic
Basic
 
VB.net
VB.netVB.net
VB.net
 
Data Types, Variables, and Operators
Data Types, Variables, and OperatorsData Types, Variables, and Operators
Data Types, Variables, and Operators
 
Java data types, variables and jvm
Java data types, variables and jvm Java data types, variables and jvm
Java data types, variables and jvm
 
Android Training (Java Review)
Android Training (Java Review)Android Training (Java Review)
Android Training (Java Review)
 
Java
JavaJava
Java
 

Java Basics

  • 1. Basic JAVA Write once run any where
  • 2. 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.
  • 3. 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.
  • 4. 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
  • 5. 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[])
  • 6. 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.
  • 7. [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
  • 8. 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
  • 9. 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
  • 10.  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
  • 11. 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.
  • 12. 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);
  • 13. 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
  • 14. 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
  • 15. 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
  • 16. 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
  • 17. 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.
  • 18. 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>
  • 19. 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
  • 20. 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.
  • 21. 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.
  • 22.  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
  • 23. 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.
  • 24. 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.
  • 25. 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.
  • 26. 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]
  • 27. 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
  • 28. 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.
  • 29. 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
  • 30. 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
  • 31. 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.
  • 32. 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
  • 33. 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.
  • 34. 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
  • 35. 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.
  • 36.  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.
  • 37. This was my first KT. Given in honing solutions in 2006.