Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 67

Introduction

Why Java is Important?


• Two reasons :
– Trouble with C/C++ language is that they are not
portable and are not platform independent
languages.
– Emergence of World Wide Web, which demanded
portable programs
• Portability and security necessitated the
invention of Java
History
• James Gosling - Sun Microsystems
• Co founder – Vinod Khosla
• Oak - Java, May 20, 1995, Sun World
• JDK Evolutions
– JDK 1.0 (January 23, 1996)
– JDK 1.1 (February 19, 1997)
– J2SE 1.2 (December 8, 1998)
– J2SE 1.3 (May 8, 2000)
– J2SE 1.4 (February 6, 2002)
– J2SE 5.0 (September 30, 2004)
– Java SE 6 (December 11, 2006)
– Java SE 7 (July 28, 2011) and so on……
Current Version
???
Cont..
• Java Editions.
 J2SE(Java 2 Standard Edition) - to develop
client-side standalone applications or applets.
 J2ME(Java 2 Micro Edition ) - to develop
applications for mobile devices such as cell
phones.
 J2EE(Java 2 Enterprise Edition ) - to develop
server-side applications such as Java servlets
and Java ServerPages.
What is java?

• A general-purpose object-oriented language.

• Write Once Run Anywhere (WORA).

• Designed for easy Web/Internet applications.


Java is architecture-neutral

JAVA Program Execution

9/15/2011 17
WORA(Write Once Run Anywhere)

18
JVM
• JVM (Java Virtual Machine) is an abstract machine that enables your
computer to run a Java program.

• When you run the Java program, Java compiler first compiles your Java
code to bytecode. Then, the JVM translates bytecode into native machine
code

• When you run the Java program, Java compiler first compiles your Java
code to bytecode. Then, the JVM translates bytecode into native machine
code.

• Java is a platform-independent language. It's because when you write


Java code, it's ultimately written for JVM but not your physical machine
(computer). Since JVM ​executes the Java bytecode which is platform-
independent, Java is platform-independent.
Java Runtime Environment
• JRE (Java Runtime Environment) is a software
package that provides Java class libraries, Java
Virtual Machine (JVM), and other components
that are required to run Java applications.
Java Development Kit
• Jdk is collection of classes, java compiler and jvm
interpreter.

• JDK (Java Development Kit) is a software development


kit required to develop applications in Java. When you
download JDK, JRE is also downloaded with it.

• In addition to JRE, JDK also contains a number of


development tools (compilers, JavaDoc, Java Debugger,
etc).
Relationship between JVM, JRE, and JDK.
Just In Time (JIT)
• In some cases JVM is slow.
• Bytecode must be interpreted at runtime.
• Java also provide local compiler that convert byte
code into executable for faster running which is
know as JIT.
Java Standard Library
• Java API is collection classes and methods group in
the form of packages. JDk 1.2 has 58 packages, it is
also know as Java standard library.

a) Java.lang: wrappers, strings and basic features of


java
b) Java.util: provide classes that support date, time
etc.
c) Java.io: reading and writind data
d) Java.awt: classes for creating GUI
e) Java.applet
f) Javax.swing
Characteristics of Java
• Java is platform • Java is portable
independent • Java is multithreaded
• Java is object-oriented • Java is dynamic
• Java is distributed • Java is secure
• Java is compiler and
interpreted
• Java is robust
Hello.java
public class Hello
{
//-----------------------------------------------------------------
// Prints a presidential quote.
//-----------------------------------------------------------------
public static void main (String[] args)
{
System.out.print (“Hello");

System.out.println (“How are you?");


}
}
Java Program Structure
// comments about the class
public class MyProgram
{
Class Name

class body

Comments can be placed almost anywhere


}
Java Program Structure
// comments about the class
public class MyProgram
{

// comments about the method


public static void main (String[] args)
{
method header
method body
}

}
Setting Variable Environment
Temporary:
To set the temporary path of JDK, you need to follow the following
steps:
• Open the command prompt
• Copy the path of the JDK/bin directory
• Write in command prompt: set path=copied_path
set path=C:\Program Files\Java\jdk1.8.0_191\bin
Permanent:
For setting the permanent path of JDK, you need to follow these
steps:
• Go to MyComputer properties -> advanced tab -> environment
variables -> new tab of system variable -> write path in variable
name -> write path of bin folder in variable value -> ok -> ok -> ok
19
How is Java different from C…
• C Language:
– Major difference is that C is a structure oriented language and
Java is an object oriented language and has mechanism to define
classes and objects.
– Java does not support an explicit pointer type
– Java does not have preprocessor, so we cant use #define,
#include and #ifdef statements.
– Java does not include structures, unions data types.
– Java does not include keywords like goto, sizeof and typedef.
– Java adds labeled break and continue statements.
– Java adds many features required for object
oriented programming.
How is Java different from C++…
• C++ language
Features removed in java:
 Java doesn’t support pointers to avoid unauthorized access
of memory locations.
 Java does not include structures, unions data types.
 Java does not support operator over loading.
 Preprocessor plays less important role in C++
and so eliminated entirely in java.
 Java does not perform automatic type
conversions that
result in loss of precision.
Cont…
 Java does not support global variables. Every
method and variable is declared within a class and
forms part of that class.
 Java does not allow default arguments.
 Java does not support inheritance of multiple super
classes by a sub class (i.e., multiple inheritance). This is
accomplished by using ‘interface’ concept.
 It is not possible to declare unsigned integers in java.
 In java objects are passed by reference only. In C++
objects may be passed by value or reference.
Cont …
New features added in Java:

 Multithreading, that allows two or more pieces of the


same program to execute concurrently.
 C++ has a set of library functions that use a common
header file. But java replaces it with its own set of API
classes.
 It adds packages and interfaces.
 Java supports automatic garbage collection.
 break and continue statements have been enhanced in
java to accept labels as targets.
Cont …
Features that differ:

 Though C++ and java supports Boolean data type, C++ takes
any nonzero value as true and zero as false. True and false in
java are predefined literals that are values for a boolean
expression.
 Java has replaced the destructor function with a finalize()
function.
 C++ supports exception handling that is similar to java's.
However, in C++ there is no requirement that a thrown
exception be caught.
Comments
Comments in a program are called inline documentation
They should be included to explain the purpose of the
program and describe processing steps
They do not affect how a program works
Java comments can take three forms:

// this comment runs to the end of the line

/* this comment runs to the terminating


symbol, even across line breaks */

/** this is a javadoc comment */


Identifiers
Identifiers are the words a programmer uses in a program
An identifier can be made up of letters, digits, the
underscore character ( _ ), and the dollar sign
Identifiers cannot begin with a digit
Java is case sensitive - Total, total, and TOTAL
are different identifiers
By convention, programmers use different case styles for
different types of identifiers, such as

title case for class names - Lincoln


upper case for constants - MAXIMUM 1-26
Reserved Words
The Java reserved words:
abstract else interface switch
assert enum long synchronized
boolean extends native this
break false new throw
byte final null throws
case finally package transient
catch float private true
char for protected try
class goto public void
const if return volatile
continue implements short while
default import static
do instanceof strictfp
double int super
Primitive Types
boolean 8 bits (1 byte)
char 16 bits (2 bytes)
byte 8 bits (1 byte)
short 16 bits (2 bytes)
int 32 bits (4 bytes)
long 64 bits (8 bytes)
float 32 bits (4 bytes)
double 64 bits (8 bytes)

Guaranteed to occupy same number of bits regardless of


platform
byte
 Smallest integer type
 It is a signed 8-bit type (1 Byte)
 Range is -128 to 127
 Especially useful when working with stream of data from a
network or file
 Default value = 0
 Example:
byte b = 10;
short
 short is signed 16-bit (2 Byte) type
 Range : -32768 to 32767
 It is probably least used Java type
 Default value = 0
 Example:
short vId = 1234;
int
 The most commonly used type
 It is signed 32-bit (4 Byte) type
 Range: -2,147,483,648 to 2,147,483,647
 Default value = 0
 Example:
int a = 1234;
long
 long is signed 64-bit (8 Byte) type
 It is useful when int type is not large enough to hold the desired
value
 Default value = 0L
 Example:
long soconds = 1234124321L;
char
 It is 16-bit (2 Byte) type
 Not like c/c++ (in c/c++ it is only 1Byte)
 Because java is uses Unicode to represent all the character set
 Range: 0 to 65,536
 Default value = ‘\u0000’
 Example:
char first = ‘A’;
char second = 65;
float
 It is 32-bit (4-Byte) type
 It specifies a single-precision value
 Default value = 0.0f
 Example:
float price = 1234.45213f; output = 1123.4521
float price = 12345.45213f;
Haveoutput = f12345.452
to write at
the end
double
 It uses 64-bit (8-Byte)
 All math functions such as sin(),cos(),sqrt() etc… returns double
value
 Default value = 0.0d
 Example:
double pi = 3.14141414141414;
boolean
 The Boolean data type is used to store only two possible values: true and false.
 This data type is used for simple flags that track true/false conditions.
 The Boolean data type specifies one bit of information, but its "size" can't be defined precisely.
 Default Value = false
 Example:
boolean a = true;
Strings
Java defines the String class to handle strings
A String is a collection of characters treated as a single unit
It is not an array of char variables
Multiple String constructors
String s2 = “Hello World”;
Type Casting
Assigning a value of one type to a variable of another type
is known as Type Casting.
Syntax:

dataType variableName = (dataType) variableToConvert;

Type casting are of two types they are


Implicit Casting (Widening)
Explicit Casting (Narrowing)
Implicit Casting in Java / Widening / Automatic type conver

Automatic type conversion can happen if both type are


compatible and target type is larger than source type.
Explicit Casting in Java / Narrowing
When you are assigning a larger type to a smaller type,
then Explicit Casting is required.
Type promotion in Expressions
 While evaluating expressions, the intermediate value may exceed the
range of operands and hence the expression value will be promoted.
Some conditions for type promotion are:
 Java automatically promotes each byte, short, or char operand to
int when evaluating an expression.
 If one operand is a long, float or double the whole expression is
promoted to long, float or double respectively.
For example:

char c = 'a';
short s = 1024;
int i = 50000;
float f = 5.67f;
double d = 1.1234;
// The Expression
Type promotion in
//Java program to illustrate Type promotion in Expressions
class Test

public static void main(String args[])

byte b = 42;

double result = (f * b) + (i / c) - (d * s);


//Result after all the promotions are done

Expressions
System.out.println("result = " + result);
}
} //In this, it will directly convert it into double as a larger data type.
Types of operators:
Java language offers many types of operators. They are,
Arithmetic operators
Assignment operators
Relational operators
Logical operators
Bit wise operators
Conditional operators (ternary operators)
Increment/decrement operators
Special operators
Arithmetic Operators in Java:
Arithmetic operators are used to perform mathematical
calculations like addition, subtraction, multiplication, division
and modulus in Java programs.

S.no Arithmetic Operators Operation Example

1 + Addition A+B

2 – Subtraction A-B

3 * multiplication A*B

4 / Division A/B

5 % Modulus A%B
Assignment Operators in Java
In Java programs, values for the variables are assigned using
assignment operators.

Operators Example Explanation


Simple assignment
= sum = 10 10 is assigned to variable sum
operator
+= sum += 10 This is same as sum = sum + 10
-= sum -= 10 This is same as sum = sum – 10
*= sum *= 10 This is same as sum = sum * 10
Compound assignment
/+ sum /= 10 This is same as sum = sum / 10
operators
%= sum %= 10 This is same as sum = sum % 10
&= sum&=10 This is same as sum = sum & 10
^= sum ^= 10 This is same as sum = sum ^ 10
Relational operators in Java
Relational operators are used to find the relation between
two variables. i.e. to compare the values of two variables in a
Java program.

S.no Operators Example Description


1 > x>y x is greater than y
2 < x<y x is less than y
3 >= x >= y x is greater than or equal to y
4 <= x <= y x is less than or equal to y
5 == x == y x is equal to y
6 != x != y x is not equal to y
Logical operators in Java

These operators are used to perform logical operations on


the given expressions.

S.
Operators Name Example Description
no

logical
1 && (x>5)&&(y<5) It returns true when both conditions are true
AND

logical It returns true when at-least one of the


2 || (x>=10)||(y>=10)
OR condition is true

It reverses the state of the operand


logical “((x>5) && (y<5))”
3 ! !((x>5)&&(y<5))
NOT If “((x>5) && (y<5))” is true, logical NOT
operator makes it false
Bit wise operators in Java
These operators are used to perform bit operations. Decimal
values are converted into binary values which are the
sequence of bits and bit wise operators work on these bits.

x y x|y x&y x^y Operator_symbol Operator_name


0 0 0 0 0 & Bitwise_AND
0 1 1 0 1 | Bitwise OR
1 0 1 0 1 ~ Bitwise_NOT
1 1 1 1 0 ^ XOR
<< Left Shift
>> Right Shift
Conditional or ternary operators in Java

Conditional operators return one value if condition is true and


returns another value if condition is false.
This operator is also called as ternary operator.
Syntax :
(Condition? true_value: false_value);
Example:
(A >100 ? 0 : 1);
In above example, if A is greater than 100, 0 is returned
else 1 is returned. This is equal to if else conditional
statements.
Increment/decrement Operators in Java

Increment operators are used to increase the value of the


variable by one and decrement operators are used to
decrease the value of the variable by one in Java programs.
Syntax:
Increment operator:
++var_name; (or) var_name++;
Decrement operator:
--var_name; (or) var_name--;
Difference between pre/post increment & decrement
operators in Java:

S.no Operator type Operator Description


++i Value of i is incremented before
1 Pre increment
assigning it to variable i.
i++ Value of i is incremented after assigning
2 Post–increment
it to variable i.
--i Value of i is decremented before
3 Pre decrement
assigning it to variable i.
i-- Value of i is decremented after assigning
4 Post_decrement
it to variable i.
Decision and control structure
The Java if statement is used to test the condition. It checks boolean
condition: true or false.
There are various types of if statement in java.

Java if statement: Java if-else-if ladder statement: Java nested if


if(condition){ if(condition1){ statement:
// //to be executed if c1 is true if(condition){
code to be executed }else if(condition2){ //
} //to be executed if c2 is true code to be executed
Java if-else statement: }
if(condition){ else if(condition3){ if(condition){
//code if condition is true //to be executed if c3 is true //
}else{ } code to be executed
//code if condition is false ...
} else{ }
// }
to be executed if all the conditions
are false
}
Labelled Continue
Labelled Break
Decision and control structure
Java Switch statement:
 The Java switch statement executes one statement from multiple conditions. It is like if-else-if ladder statement. The switch statement works with byte, short, int, long, enum types, String and some wrapper types
like Byte, Short, Int, and Long.
 Since Java 7, you can use strings in the switch statement.
 In other words, the switch statement tests the equality of a variable against multiple values.
Decision and control structure
Java Switch statement:
 There can be one or N number of case values for a switch expression.
 The case value must be of switch expression type only. The case value must be literal or constant. It doesn't allow variables.
 The case values must be unique. In case of duplicate value, it renders compile-time error.
 The Java switch expression must be of byte, short, int, long (with its Wrapper type), enums and string.
 Each case statement can have a break statement which is optional. When control reaches to the break statement, it jumps the control after the switch expression. If a break statement is not found, it executes the next case.
 The case value can have a default label which is optional.
Decision and control structure

Java Switch statement:


switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
//code to be executed if all cases are not matched;
}
Decision and control
structure

Example:
public class SwitchStringExample
{
public static void main(String[] args)
{
String levelString="Expert"; int level=0;
switch(levelString)
Decision and control structure
• In programming languages, loops are used to
execute a set of instructions/functions repeatedly
when some conditions become true.
• There are three types of loops in java.
 for loop
 while loop
 do-while loop
Java For Loop vs While Loop vs Do While Loop
Comparison for loop while loop do while loop
Introduction The Java for loop is a control The Java while loop is a The Java do while loop is a control
flow statement that iterates a control flow statement that flow statement that executes a part
part of the programs multiple executes a part of the of the programs at least once and
times. programs repeatedly on the the further execution depends
basis of given boolean upon the given boolean condition.
condition.

When to use If the number of iteration is If the number of iteration is If the number of iteration is not
fixed, it is recommended to use not fixed, it is recommended fixed and you must have to execute
for loop. to use while loop. the loop at least once, it is
recommended to use the do-while
loop.

Syntax for(init;condition;incr/decr){ // while(condition){ //code to do{ //code to be


code to be executed } be executed } executed }while(condition);

Example //for loop //while loop //do-while loop


for(int i=1;i<=10;i++) int i=1; while(i<=10) int i=1; do{ System.out.println(i); i+
{ System.out.println(i); } { System.out.println(i); i++; } +; }while(i<=10);

Syntax for infinitive for(;;){ //code to be executed } while(true){ //code to be do{ //code to be
loop executed } executed }while(true);
Command-line argument
 The java command-line argument is an argument i.e. passed
at the time of running the java program.

 The arguments passed from the console can be received in the


java program and it can be used as an input.
Command-line argument
Command-line argument
Java For-each loop
The for-each loop is used to traverse array or collection in java. It is easier
to use than simple for loop because we don't need to increment value and
use subscript notation.

It works on elements basis not index. It returns element one by one in the
defined variable.

Syntax:
for(Type var:array){
//code to be executed
}
Example:
int arr[]={12,23,44,56,78};
//Printing array using for-each loop
for(int i:arr){
System.out.println(i);
}
Limitations of For-each loop
Limitations of For-each loop

You might also like