Upload
susanna-caldwell
View
230
Download
1
Embed Size (px)
Citation preview
Chapt. 1
Introduction to Core Java
Lecture 1: Overview of Java
Introduction
Java is a programming language invented by James Gosling and others in 1994.
originally named Oak ,was developed as a part of the Green project at the Sun Company.
A general-purpose object-oriented language
Based on C/C++.
Designed for easy Web/Internet applications.
Widespread acceptance.
Java FeaturesJava is simple
Java is object-oriented
Java is distributed
Java is interpreted
Java is robust
Java is secure
Java is architecture-neutral
Java is portable
High performance
Java is multithreaded
Java is dynamic
Java Features Simple
fixes some clumsy features of C++ no pointers automatic garbage collection rich pre-defined class library http://java.sun.com/j2se/1.4.2/docs/api/
Object oriented focus on the data (objects) and methods manipulating the data all functions are associated with objects almost all datatypes are objects (files, strings, etc.) potentially better code organization and reuse
Complied and Interpreted java compiler generate byte-codes, not native machine code the compiled byte-codes are platform-independent java bytecodes are translated on the fly to machine readable
instructions in runtime (Java Virtual Machine)
Platform Independent and Portable same application runs on all platforms the sizes of the primitive data types are always the same the libraries define portable interfaces .
Java Features
OS/Hardware
machine codeC source code
myprog.cgcc
myprog.exe
Platform Dependent
JVM
bytecodeJava source code
myprog.javajavac
myprog.class
OS/Hardware
Platform Independent
Java Features
Reliable (Robust) extensive compile-time and runtime error checking. no pointers but real arrays. Memory corruptions or unauthorized
memory accesses are impossible. automatic garbage collection tracks objects usage over time.
Secure usage in networked environments requires more security. memory allocation model is a major defense. access restrictions are forced (private, public).
Java Features
Multithreaded and Interactive multiple concurrent threads of executions can run
simultaneously utilizes a sophisticated set of synchronization primitives (based
on monitors and condition variables paradigm) to achieve this . Hence improves the interactive performance of graphics
application.
Dynamic and Extensible java is designed to adapt to evolving environment. libraries can freely add new methods and instance variables
without any effect on their clients. interfaces promote flexibility and reusability in code by specifying
a set of methods an object can perform, but leaves open how these methods should be implemented.
Java Features (4)Dynamic and Extensible
Functions written in other languages can be accessed in java program can check the class type in runtime
Distributed Designed for creating applications on networks. Can access remote object on Internet as easily as they can do in a local system. Hence enables multiple programmer at multiple remote places can work on single project together.
High Performanceo Java performance is impressive due to use of byte code and multithreading.
Java Features
Architecture-Neutralo Write once, run anywhere any time, forever.
JDK Environment & toolsJDK comes with a collection of tools that are used for
developing and running java programs.
Sr. No Tool Description
1 Applet viewer Enables to run Java applets.
2 Java Java Interpreter runs application programs and applet by reading bytecode.
3 Javac Java complier translate source code to byte code.
4 Javadoc Creates HTML documents from Java source code files.
5 Javah Produces header files for use with native methods
6 javap Java disassembler convert bytecode files into program description
7 jdb Java debugger which helps us to find errors in our programs
Application Program InterfaceJava Standard library (API) includes hundreds of classes
methods grouped into several packages.Sr.No
Package Description
1 Language Support Package
Required for implementing basic features of java.
2 Utilities Package Provides utility functions such as date and time functions.
3 Input/output Package Required for input/output manipulation.
4 Networking Package Enables to communicate with other computers via Internet.
5 AWT Package The abstract Window Toolkit package contains classes that implements platform-independent GUI.
6 Applet Package Includes set of classes that allows us to create Java applets.
Object Oriented Concepts with respect to javaClass
A blueprint that defines the attributes and methods
ObjectAn instance of a Class
AbstractionHide certain details and show only essential details
EncapsulationBinding data and methods together
InheritanceInherit the features of the superclass
PolymorphismOne name having many forms
Difference between c++ & java
Java is truly object oriented.Java does not support operater overloading.Java does not have template classes as in c++Java does not support multiple inheritance of
classes. But can be achieved by using interface.Java does not support global variables. Every
variable and method is declared within a class and forms part of that class.
Java does not use pointer.
Difference between c++ & java
Java has relacesd destructor function with finalize() function.
There are no header files in java.
Appendix A: Introduction to Java 17
how Java Works?
Install JavaTM 2 Platform on your machine
Can be installed on different platforms: Unix/Linux Windows Mac OS
Follow the on-line instructions:http://java.sun.com/docs/books/tutorial/getStarted/cupojava/index.html
Getting Started:
(1) Create the source file: open a text editor, type in the code which defines a class
(HelloWorldApp) and then save it in a file (HelloWorldApp.java) file and class name are case sensitive and must be matched
exactly (except the .java part)
Example Code: HelloWorldApp.java
/** * The HelloWorldApp class implements an application * that displays "Hello World!" to the standard output */ class HelloWorldApp {
public static void main(String[] args) { // Display "Hello World!" System.out.println("Hello World!");
} }
Java is CASE SENSITIVE!
Getting Started:
(2) Compile the program: compile HelloWorldApp.java by using the following command:
javac HelloWorldApp.java
it generates a file named HelloWorldApp.class
‘javac’ is not recognized as an internal or external command, operable program or hatch file.
javac: Command not found
if you see one of these errors, you have two choices:1) specify the full path in which the javac program locates every time. For example:
C:\j2sdk1.4.2_09\bin\javac HelloWorldApp.java
2) set the PATH environment variable
Getting Started:
(3) Run the program: run the code through:
java HelloWorldApp
Note that the command is java, not javac, and you refer to
HelloWorldApp, not HelloWorldApp.java or HelloWorldApp.class
Exception in thread "main" java.lang.NoClassDefFoundError:
HelloWorldApp
if you see this error, you may need to set the environment variable
CLASSPATH.
Java Programming Fundamentals
Structure of Java ProgramData TypesVariablesOperatorsKeywords
General Structure of Program
Documentation Section
Package Statement
Import Statement
Main Method Class {
Main Method definition }
Interface Statement
Class Definition
suggested
Optional
Optional
Optional
Optional
Essential
Java Tokens
Smallest Individual unit in Java Program is called as Java Tokens
Java includes five types of tokenso Reserved Keywords.o Identifierso Literals o Operatorso Separators
25
Java Keywords
abstract boolean break byte case catch char
class const continue default do double else
extends final finally float for goto if
implements import instanceof int interface long native
new package private protected public return short
static strictfp super switch synchronized
this throw
throws transient try void volatile while assert
Variables
Variables:NameTypeValue
Naming:May contain numbers, underscore, dollar sign, or
lettersCan not start with numberCan be any lengthReserved keywordsCase sensitive
Data Types
Primitive(built-in)Non Primitive(Derived)
ArraysClassesInterface
Primitive data typesData Types Bit Min Value Max Value
Byte 8 -27 or (-128) 27-1 0r(127)
Short 16 -215 or(-32768) 215-1 or(32767)
Int 32 -231 231-1
Long 64 -231 231-1
Float 32 3.4e-038 3.4e+038
Double 64 1.7e-308 1.7e+308
Boolean 1 true false
Char 16
29
Definition: An operator performs a particular operation on the operands it is applied on
Types of operatorsAssignment OperatorsArithmetic OperatorsUnary OperatorsEquality OperatorsRelational OperatorsConditional Operatorsinstaceof OperatorBitwise OperatorsShift Operators
Operators - Types
30
Assignment Operator
Arithmetic Operators
Operator Description Example
= Assignment int i = 10;int j = i;
Operators – Assignment Operators/Arithmetic Operators
Operator Description Example
+ Addition int i = 8 + 9; byte b = (byte) 5+4;
- Subtraction int i = 9 – 4;
* Multiplication int i = 8 * 6;
/ Division int i = 10 / 2;
% Remainder int i = 10 % 3;
31
Unary Operators
Operator Description Example
+ Unary plus int i = +1;
- Unary minus int i = -1;
++ Increment int j = i++;
-- Decrement int j = i--;
! Logical Not boolean j = !true;
Operators – Unary Operators/Equality Operators
Operator Description Example
== Equality If (i==1)
!= Non equality If (i != 4)
• Equality Operators
32
Relational Operators
Operator Description Example
> Greater than if ( x > 4)
< Less than if ( x < 4)
>= Greater than or equal to if ( x >= 4)
<= Less than or equal to if ( x <= 4)
Operators – Relational Operators/Conditional Operators
Operator Description Example
&& Conditional and If (a == 4 && b == 5)
|| Conditional or If (a == 4 || b == 5)
• Conditional Operators
33
instanceof Operator
Operator Description Example
instanceof
Instamce of If (john instanceof person)
Operators – instanceof Operator/Bitwise Operators/shift operators
Operator Description Example
& Bitwise and 001 & 111 = 1
| Bitwise or 001 | 110 = 111
^ Bitwise ex-or 001 ^ 110 = 111
~ Reverse ~011 = -10
• Bitwise Operators
• Shift Operators
Operator Description Example
>> Right shift 4 >> 1 = 100 >> 1 = 010 = 2
<< Left Shift 4 << 1 = 100 << 1 = 1000 = 8
>>> Unsigned Right shift
4 >>> 1 = 100 >>> 1 = 010 = 2
Increment Operator: ++
m++; ++m Decrement operator:--
m--;--mConditional Operator
exp?exp2:exp3Dot Operator
person. age, person. Salary();
Operators – Increment Operators/Decrement Operators /Conditional Operators
Java Expression
36
Flow Control – if-else if-else
if-else
Syntax Example
if (<condition-1>) { // logic for true condition-1 goes here} else if (<condition-2>) { // logic for true condition-2 goes here} else { // if no condition is met, control comes here}
int a = 10;if (a < 10 ) { System.out.println(“Less than 10”);} else if (a > 10) { System.out.pritln(“Greater than 10”);} else { System.out.println(“Equal to 10”);}
Result: Equal to 10s
37
Flow Control – switch
Syntax Example
switch (<value>) { case <a>: // stmt-1 break; case <b>: //stmt-2 break; default:
//stmt-3
int a = 10;switch (a) { case 1: System.out.println(“1”); break; case 10: System.out.println(“10”); break; default: System.out.println(“None”);
Result: 10
• switch
38
Flow Control – do-while / while
do-while
Syntax Example
do { // stmt-1} while (<condition>);
int i = 0;do {System.out.println(“In do”); i++;} while ( i < 10);
Result: Prints “In do” 11 times
• whileSyntax Example
while (<condition>) {//stmt
}
int i = 0;while ( i < 10 ) { System.out.println(“In while”); i++;}
Result: “In while” 10 times
39
Flow Control – for loop
for
Syntax Example
for ( initialize; condition; expression){ // stmt}
for (int i = 0; i < 10; i++){ System.out.println(“In for”);}
Result: Prints “In do” 10 times