KEMBAR78
Java fundamentals - Basic concepts of Java | PDF
UNIT – I
JAVA FUNDAMENTALS
Chapter 1 - Java Programming
Fundamentals 1
Java features – Java Platform – Java
Fundamentals – Expressions, Operators, and
Control Structures – Classes, Packages and
Interfaces – Exception Handling.
Java Features
General Purpose OOP language
Developed Sun Microsystem of USA in 1991.
James Gosling and Patrick Naughton
Java Features
❖ Compiled and Interpreted
❖ Object-Oriented language
❖ Platform Independent & Portable
❖ Robust and Secure
❖ Distributed
❖ Automatic garbage collection
❖ Multithreaded language
❖ Dynamic and Extensible
Chapter 1 - Java Programming
Fundamentals
2
Java Platform
It include development tools and classes and
methods.The development tools are part of the
system known as Java Development Kit(JDK) and
classes and methods are part of the Java Standard
Library(JSL) also known as API.
JDK
❖ Appletviewer(for viewing java applet)
❖ Javac(Java compiler)
❖ Java(Java interpreter)
❖ Javah(for C header files)
❖ Javadoc(for creating html doc)
❖ Jdb(java debugger)
Chapter 1 - Java Programming
Fundamentals
3
API
❖ Language support package
Collection of classes and methods to implement
basic features of Java
❖ Utilities Package
Collection of classes to provide utility fn like date
and time
❖ Input/Output packages
Collection of classes required IO manipulation
Chapter 1 - Java Programming
Fundamentals
4
API
❖ AWT packages
Collection of Classes to implement platform
independent graphical user interface
❖ Applet Package
Classes used to create applets
❖ Networking Package
Collection of class computing with other
computer via internet
Chapter 1 - Java Programming
Fundamentals
5
API
Chapter 1 - Java Programming
Fundamentals
6
Source Code
Text Editor
Class File
Javac
Java
Prg O/P
Javadoc HTML File
javah Header File
jdb
API
Implementing Java Program
1.Create Java program
<filename>.java -filename same as class name
2.Compiling the program
Javac <filename>.java –java compiler converts sourcecode
into bytecode
And stored in class file like <filename>.class
3.Running the program
Java <filename> - It reads the bytecode and translate into
machine code for the specific machine on which java
program is running
Chapter 1 - Java Programming
Fundamentals
7
JVM
Java program---Java Compiler----virtual machine
Bytecode-----Java Interpreter-------machine code
Java compiler produces intermediate code known as
byte code for a machine which does not exist is
known as JVM and it exists only inside the
computer memory
Chapter 1 - Java Programming
Fundamentals
8
Fundamental Programming
Structures
• Datatype
• Variable name
• Operators
• Expressions
• Control structure
• Building a Java class
• Using Java variables and data types
• Method Definitions
• Computing with Java
• Packages and interface
• Exception handling
Structure of Java Program
Documentation section
Package Statement
Import statement
Interface statement
Class definition
Main method
{
}
Building a Java Class
• Comments
– Single line
•// compiler ignores everything to end of line
– Multi-line
•/* compiler ignores everything in between */
Data Types
• Declaring Variables
– Variable data type must be declared prior to initialization
– There are two basic data types:
• Primitive data types
– Eight available primitive data types
– Primitive data types are not capitalized in variable declarations
» int aNumber = 5;
• Reference data types
– These data types are capitalized.
» String s = “example string”;
Data Types
• Using Reference Variables
–Uses class name as a data type
–Points to an instance of that class
–Example:
»String s = “Hello World”;
»Employee emp1;
Variable Definitions
• Variable definitions
– Variable: name of place in memory that can contain data
– All variables have:
• Data type → kind of data variable can contain
• Name → identifier that refers to the variable
• Value → the default or specified value
– also called the literal of the statement
• Semicolon
– Remember: All java statements end with a semicolon!
– e.g.
• String s = “MC697”;
• int count = 5;
Step1-All identifiers should begin with a
letter (A to Z or a to z), currency character
($) or an underscore (_).
Step 2 − After the first character,
identifiers can have any combination of
characters.
Step 3 − A keyword cannot be used as an
identifier.
Step 4 − Most importantly, identifiers are
case sensitive
Chapter 1 - Java Programming
Fundamentals
16
Variable Definitions
• Initializing Variables
– Assignment operator (=)
• Used to assign value to a variable
– char c = ‘a’; - note the single quotes
– boolean b = true;
– double d = 1.25;
• Important: This is different from the comparative
equals (==)
• If variable is not initialized, most will default to
null.
All variables should be initialized.
Variable Constants
• Using Constants
– Variable with a value that doesn’t change
– Keyword
• final
– Denotes value cannot change
– Example:
• final double SALES_TAX_RATE = 4.5;
• note the naming convention
• other examples?
Operators
• Arithmetic operators
• Relational operators
• Logical operators
Chapter 1 - Java Programming
Fundamentals
19
Artithmetic operators:
• Arithmetic operators are used in
mathematical expressions in the same way
that they are used in algebra.
Chapter 1 - Java Programming
Fundamentals
20
Example
int a = 1 + 1;int b = a * 3;
int c = b / 4;
int d = c - a;
int e = -d;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
System.out.println("e = " + e);
Chapter 1 - Java Programming
Fundamentals
22
Relational operator:
The relational operators determine the relationship that one
operand has to the other.
Specifically, they determine equality and ordering. The
relational operators are shown here:
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
Chapter 1 - Java Programming
Fundamentals
23
Logical operators:
The Boolean logical operators shown here
operate only on boolean operands. All of
the binary logical operators combine two
boolean values to form a resultant
boolean value.
• & Logical AND
• | Logical OR
• ! Logical NOT
Chapter 1 - Java Programming
Fundamentals
24
Expressions
An expression is a construct made up of
variables, operators, datatype, constants
according to the syntax of the language.
Example:
int c=0;
– int --- Datatype
– C --- variable
– = --- Operator
– 0 --- Constant
Chapter 1 - Java Programming
Fundamentals
25
Building a Java Class
• Previous lab and homework demonstrated a simple Java
application.
public class HelloWorld {
public static void main(String[] args) {
System.out.println(“Hello World”);
}
}
• Be familiar with the basic components of this sample. All
applications will have this framework.
Control structure
• Conditional Statement
if
if else
else if
switch
• Iteration statement
For
While
Do while
Break and continue
Chapter 1 - Java Programming
Fundamentals
27
If statement
The if construct is used if we wish to execute
a statement only if a condition is true.
Thebasic format of the if statement is
if (condition)
{
one or more statements to be executed if
condition is true;
}
Chapter 1 - Java Programming
Fundamentals
28
If else statement
The if else construct is used if we wish to execute one set of
statements if a condition is true, and a second set of
statements if the condition is false. The basic format of the
if else construct is as follows:
if (condition)
{
one or more statements to be executed if
condition is true;
}
else
{
one or more statements to be executed if condition is false;
} Chapter 1 - Java Programming
Fundamentals
29
Else if statement
if (condition1)
{
one or more statements to be executed if condition1 is true;
}
else if (condition2)
{
one or more statements to be executed if condition1 is false
and condition2 is true;
}
else
{
} Chapter 1 - Java Programming
Fundamentals
30
Switch statement
switch (expression1) {
case value1:
one or more statements to be executed;
break;
case value2:
one or more statements to be executed;
break;
default:
one or more statements to be executed;
}
Chapter 1 - Java Programming
Fundamentals
31
While loop
The syntax of a while loop is
while (boolean expression)
{
one or more statements;
}
The block of statements is repeatedly
executed while the boolean expression
evaluates to true.
Chapter 1 - Java Programming
Fundamentals
32
Do while loop
The syntax of a do while loop is
do {
one or more statements;
}
while (boolean expression) ;
Unlike a while loop, a do while loop is
guaranteed to execute at least once.
Chapter 1 - Java Programming
Fundamentals
33
For loop
Where the iteration is over a range of values, a
for loop is a more compact alternative to a
while or do while loop. The syntax is
for (initialization expression;
test expression;
increment expression)
{
one or more statements;
}
Chapter 1 - Java Programming
Fundamentals
34
Computing with Java
• Special Operators
– For writing shortcut code
• Increment operator (++)
– Add one to a variable
• Decrement operator (--)
– Subtract one from a variable
• Assignment operator with arithmetic operators:
total = total + 5;
What is another way of writing this statement?
Classes
Class classname [extends superclassname]
{
[variable declaration;]
[methods declaration;]
}
Chapter 1 - Java Programming
Fundamentals
37
Method
Datatype methodname(parameterlist)
{
Method body
}
class stu
{
int rno;
int m1;
int m2;
int total;
void getdata(int rno1,int mark1,int mark2,int tot)
{
rno=rno1;
m1=mark1;
m2=mark2; Chapter 1 - Java Programming
Fundamentals
38
total=tot;
}
void display()
{
System.out.println(rno+” “+m1+” “+m2+” “+tot);
}
}
class sample
{
public static void main(String args[])throws IOException
{
Chapter 1 - Java Programming
Fundamentals
39
Stu s=new stu();
s.getdata(4,90,80,170);
s.display();
}
}
Chapter 1 - Java Programming
Fundamentals
40
Packages
• Related classes can be grouped in a
package.
• Packages also provide a mechanism for
access control.
• We can allow classes to have unrestricted
access to each other within a package while
restricting access to classes outside the
package.
• The syntax for assigning a class to a
package is the statement
package packagename;
This must be the first statement in the class
source code.
Chapter 1 - Java Programming
Fundamentals
42
package package1;
public class sample
{
public void display()
{
System.out.println(“Hai”);
}
}
Chapter 1 - Java Programming
Fundamentals
43
import java.io.*;
import package1.*;
class packagetest
{
Public static void main(String arg[])
{
sample s=new sample();
s.display();
}
}
Chapter 1 - Java Programming
Fundamentals
44
Interface
• An interface extends the concept of an
abstract class.
• An interface consists of method
declarations; however, no method body is
included.
Chapter 1 - Java Programming
Fundamentals
45
Example:
interface PerformTransaction
{
public void deposit (double amount);
public double withdraw (double amount);
}
Chapter 1 - Java Programming
Fundamentals
46
Exception handling
• Java provides an exception-handling
mechanism that helps you build robust code.
• When an error occurs at runtime, an
exception is thrown.
• It is possible for an application to catch this
exception and, in many cases, recover from
it.
Chapter 1 - Java Programming
Fundamentals
47
• The try and catch statements allow
exceptions to be handled by the program.
• The try statement contains all the code that
may throw an exception.
• Each exception is handled by a catch
statement.
• When an exception is thrown at runtime, the
try block execution is terminated and
control is passed to the appropriate catch
statement.
Chapter 1 - Java Programming
Fundamentals
48
The form of try and catch statements is
try
{
one or more statements that may throw an
exception
}
catch (Exception e)
{
one or more statements to be executed if this
exception is thrown
} Chapter 1 - Java Programming
Fundamentals
49
The finally statement defines a block of
code that is guaranteed to execute after
leaving the try block regardless of how we
leave it.
Chapter 1 - Java Programming
Fundamentals
50
try {
one or more statements that may throw an exception
}
catch (Exception1 e) {
code to execute if Exception1 is thrown, statement a
}
catch (Exception2 e) {
code to execute if Exception2 is thrown, statement b
}
finally {
code guaranteed to execute, statement c
} Chapter 1 - Java Programming
Fundamentals
51

Java fundamentals - Basic concepts of Java

  • 1.
    UNIT – I JAVAFUNDAMENTALS Chapter 1 - Java Programming Fundamentals 1 Java features – Java Platform – Java Fundamentals – Expressions, Operators, and Control Structures – Classes, Packages and Interfaces – Exception Handling.
  • 2.
    Java Features General PurposeOOP language Developed Sun Microsystem of USA in 1991. James Gosling and Patrick Naughton Java Features ❖ Compiled and Interpreted ❖ Object-Oriented language ❖ Platform Independent & Portable ❖ Robust and Secure ❖ Distributed ❖ Automatic garbage collection ❖ Multithreaded language ❖ Dynamic and Extensible Chapter 1 - Java Programming Fundamentals 2
  • 3.
    Java Platform It includedevelopment tools and classes and methods.The development tools are part of the system known as Java Development Kit(JDK) and classes and methods are part of the Java Standard Library(JSL) also known as API. JDK ❖ Appletviewer(for viewing java applet) ❖ Javac(Java compiler) ❖ Java(Java interpreter) ❖ Javah(for C header files) ❖ Javadoc(for creating html doc) ❖ Jdb(java debugger) Chapter 1 - Java Programming Fundamentals 3
  • 4.
    API ❖ Language supportpackage Collection of classes and methods to implement basic features of Java ❖ Utilities Package Collection of classes to provide utility fn like date and time ❖ Input/Output packages Collection of classes required IO manipulation Chapter 1 - Java Programming Fundamentals 4
  • 5.
    API ❖ AWT packages Collectionof Classes to implement platform independent graphical user interface ❖ Applet Package Classes used to create applets ❖ Networking Package Collection of class computing with other computer via internet Chapter 1 - Java Programming Fundamentals 5
  • 6.
    API Chapter 1 -Java Programming Fundamentals 6 Source Code Text Editor Class File Javac Java Prg O/P Javadoc HTML File javah Header File jdb
  • 7.
    API Implementing Java Program 1.CreateJava program <filename>.java -filename same as class name 2.Compiling the program Javac <filename>.java –java compiler converts sourcecode into bytecode And stored in class file like <filename>.class 3.Running the program Java <filename> - It reads the bytecode and translate into machine code for the specific machine on which java program is running Chapter 1 - Java Programming Fundamentals 7
  • 8.
    JVM Java program---Java Compiler----virtualmachine Bytecode-----Java Interpreter-------machine code Java compiler produces intermediate code known as byte code for a machine which does not exist is known as JVM and it exists only inside the computer memory Chapter 1 - Java Programming Fundamentals 8
  • 9.
    Fundamental Programming Structures • Datatype •Variable name • Operators • Expressions • Control structure • Building a Java class • Using Java variables and data types • Method Definitions • Computing with Java • Packages and interface • Exception handling
  • 10.
    Structure of JavaProgram Documentation section Package Statement Import statement Interface statement Class definition Main method { }
  • 11.
    Building a JavaClass • Comments – Single line •// compiler ignores everything to end of line – Multi-line •/* compiler ignores everything in between */
  • 12.
    Data Types • DeclaringVariables – Variable data type must be declared prior to initialization – There are two basic data types: • Primitive data types – Eight available primitive data types – Primitive data types are not capitalized in variable declarations » int aNumber = 5; • Reference data types – These data types are capitalized. » String s = “example string”;
  • 14.
    Data Types • UsingReference Variables –Uses class name as a data type –Points to an instance of that class –Example: »String s = “Hello World”; »Employee emp1;
  • 15.
    Variable Definitions • Variabledefinitions – Variable: name of place in memory that can contain data – All variables have: • Data type → kind of data variable can contain • Name → identifier that refers to the variable • Value → the default or specified value – also called the literal of the statement • Semicolon – Remember: All java statements end with a semicolon! – e.g. • String s = “MC697”; • int count = 5;
  • 16.
    Step1-All identifiers shouldbegin with a letter (A to Z or a to z), currency character ($) or an underscore (_). Step 2 − After the first character, identifiers can have any combination of characters. Step 3 − A keyword cannot be used as an identifier. Step 4 − Most importantly, identifiers are case sensitive Chapter 1 - Java Programming Fundamentals 16
  • 17.
    Variable Definitions • InitializingVariables – Assignment operator (=) • Used to assign value to a variable – char c = ‘a’; - note the single quotes – boolean b = true; – double d = 1.25; • Important: This is different from the comparative equals (==) • If variable is not initialized, most will default to null. All variables should be initialized.
  • 18.
    Variable Constants • UsingConstants – Variable with a value that doesn’t change – Keyword • final – Denotes value cannot change – Example: • final double SALES_TAX_RATE = 4.5; • note the naming convention • other examples?
  • 19.
    Operators • Arithmetic operators •Relational operators • Logical operators Chapter 1 - Java Programming Fundamentals 19
  • 20.
    Artithmetic operators: • Arithmeticoperators are used in mathematical expressions in the same way that they are used in algebra. Chapter 1 - Java Programming Fundamentals 20
  • 22.
    Example int a =1 + 1;int b = a * 3; int c = b / 4; int d = c - a; int e = -d; System.out.println("a = " + a); System.out.println("b = " + b); System.out.println("c = " + c); System.out.println("d = " + d); System.out.println("e = " + e); Chapter 1 - Java Programming Fundamentals 22
  • 23.
    Relational operator: The relationaloperators determine the relationship that one operand has to the other. Specifically, they determine equality and ordering. The relational operators are shown here: == Equal to != Not equal to > Greater than < Less than >= Greater than or equal to <= Less than or equal to Chapter 1 - Java Programming Fundamentals 23
  • 24.
    Logical operators: The Booleanlogical operators shown here operate only on boolean operands. All of the binary logical operators combine two boolean values to form a resultant boolean value. • & Logical AND • | Logical OR • ! Logical NOT Chapter 1 - Java Programming Fundamentals 24
  • 25.
    Expressions An expression isa construct made up of variables, operators, datatype, constants according to the syntax of the language. Example: int c=0; – int --- Datatype – C --- variable – = --- Operator – 0 --- Constant Chapter 1 - Java Programming Fundamentals 25
  • 26.
    Building a JavaClass • Previous lab and homework demonstrated a simple Java application. public class HelloWorld { public static void main(String[] args) { System.out.println(“Hello World”); } } • Be familiar with the basic components of this sample. All applications will have this framework.
  • 27.
    Control structure • ConditionalStatement if if else else if switch • Iteration statement For While Do while Break and continue Chapter 1 - Java Programming Fundamentals 27
  • 28.
    If statement The ifconstruct is used if we wish to execute a statement only if a condition is true. Thebasic format of the if statement is if (condition) { one or more statements to be executed if condition is true; } Chapter 1 - Java Programming Fundamentals 28
  • 29.
    If else statement Theif else construct is used if we wish to execute one set of statements if a condition is true, and a second set of statements if the condition is false. The basic format of the if else construct is as follows: if (condition) { one or more statements to be executed if condition is true; } else { one or more statements to be executed if condition is false; } Chapter 1 - Java Programming Fundamentals 29
  • 30.
    Else if statement if(condition1) { one or more statements to be executed if condition1 is true; } else if (condition2) { one or more statements to be executed if condition1 is false and condition2 is true; } else { } Chapter 1 - Java Programming Fundamentals 30
  • 31.
    Switch statement switch (expression1){ case value1: one or more statements to be executed; break; case value2: one or more statements to be executed; break; default: one or more statements to be executed; } Chapter 1 - Java Programming Fundamentals 31
  • 32.
    While loop The syntaxof a while loop is while (boolean expression) { one or more statements; } The block of statements is repeatedly executed while the boolean expression evaluates to true. Chapter 1 - Java Programming Fundamentals 32
  • 33.
    Do while loop Thesyntax of a do while loop is do { one or more statements; } while (boolean expression) ; Unlike a while loop, a do while loop is guaranteed to execute at least once. Chapter 1 - Java Programming Fundamentals 33
  • 34.
    For loop Where theiteration is over a range of values, a for loop is a more compact alternative to a while or do while loop. The syntax is for (initialization expression; test expression; increment expression) { one or more statements; } Chapter 1 - Java Programming Fundamentals 34
  • 36.
    Computing with Java •Special Operators – For writing shortcut code • Increment operator (++) – Add one to a variable • Decrement operator (--) – Subtract one from a variable • Assignment operator with arithmetic operators: total = total + 5; What is another way of writing this statement?
  • 37.
    Classes Class classname [extendssuperclassname] { [variable declaration;] [methods declaration;] } Chapter 1 - Java Programming Fundamentals 37 Method Datatype methodname(parameterlist) { Method body }
  • 38.
    class stu { int rno; intm1; int m2; int total; void getdata(int rno1,int mark1,int mark2,int tot) { rno=rno1; m1=mark1; m2=mark2; Chapter 1 - Java Programming Fundamentals 38
  • 39.
    total=tot; } void display() { System.out.println(rno+” “+m1+”“+m2+” “+tot); } } class sample { public static void main(String args[])throws IOException { Chapter 1 - Java Programming Fundamentals 39
  • 40.
  • 41.
    Packages • Related classescan be grouped in a package. • Packages also provide a mechanism for access control. • We can allow classes to have unrestricted access to each other within a package while restricting access to classes outside the package.
  • 42.
    • The syntaxfor assigning a class to a package is the statement package packagename; This must be the first statement in the class source code. Chapter 1 - Java Programming Fundamentals 42
  • 43.
    package package1; public classsample { public void display() { System.out.println(“Hai”); } } Chapter 1 - Java Programming Fundamentals 43
  • 44.
    import java.io.*; import package1.*; classpackagetest { Public static void main(String arg[]) { sample s=new sample(); s.display(); } } Chapter 1 - Java Programming Fundamentals 44
  • 45.
    Interface • An interfaceextends the concept of an abstract class. • An interface consists of method declarations; however, no method body is included. Chapter 1 - Java Programming Fundamentals 45
  • 46.
    Example: interface PerformTransaction { public voiddeposit (double amount); public double withdraw (double amount); } Chapter 1 - Java Programming Fundamentals 46
  • 47.
    Exception handling • Javaprovides an exception-handling mechanism that helps you build robust code. • When an error occurs at runtime, an exception is thrown. • It is possible for an application to catch this exception and, in many cases, recover from it. Chapter 1 - Java Programming Fundamentals 47
  • 48.
    • The tryand catch statements allow exceptions to be handled by the program. • The try statement contains all the code that may throw an exception. • Each exception is handled by a catch statement. • When an exception is thrown at runtime, the try block execution is terminated and control is passed to the appropriate catch statement. Chapter 1 - Java Programming Fundamentals 48
  • 49.
    The form oftry and catch statements is try { one or more statements that may throw an exception } catch (Exception e) { one or more statements to be executed if this exception is thrown } Chapter 1 - Java Programming Fundamentals 49
  • 50.
    The finally statementdefines a block of code that is guaranteed to execute after leaving the try block regardless of how we leave it. Chapter 1 - Java Programming Fundamentals 50
  • 51.
    try { one ormore statements that may throw an exception } catch (Exception1 e) { code to execute if Exception1 is thrown, statement a } catch (Exception2 e) { code to execute if Exception2 is thrown, statement b } finally { code guaranteed to execute, statement c } Chapter 1 - Java Programming Fundamentals 51