SlideShare a Scribd company logo
 What is java
 History
 Java as a Programming Tool
 Advantages of Java
 The Java “White Paper” Buzzwords
 Java and the Internet
 Java is a programming language.
 It is a platform.
 Platform: Any hardware or software
environment in which a program runs, is
known as a platform.
 Since Java has its own runtime environment
(JRE) and API, it is called platform.
 According to Sun, 3 billion devices run java.
 There are many devices where java is currently
used. Some of them are as follows:
 Desktop Applications such as acrobat reader,
media player, antivirus etc.
 Web Applications such as irctc.co.in, oracle.com
etc.
 Enterprise Applications such as banking
applications.
 Mobile
 Embedded System
 Smart Card
 Robotics
 Games etc.
There are mainly 4 type of applications that can be
created using java:
1) Standalone Application
 It is also known as desktop application or
window-based application.
 An application that we need to install on every
machine such as media player, antivirus etc.
 AWT and Swing are used in java for creating
standalone applications.
2) Web Application
 An application that runs on the server side and
creates dynamic page, is called web application.
 Currently, servlet, jsp, struts, jsf etc.
technologies are used for creating web
applications in java.
3) Enterprise Application
 An application that is distributed in nature, such
as banking applications etc.
 It has the advantage of high level security, load
balancing and clustering.
 In java, EJB is used for creating enterprise
applications.
4) Mobile Application
 An application that is created for mobile
devices.
 Currently Android and Java ME are used for
creating mobile applications.
 There is given many features of java.
 They are also known as java buzzwords.
Simple Object-Oriented
Platform independent Secured
Robust Architecture neutral
Portable Dynamic
Multithreaded High Performance
Interpreted Distributed
 According to Sun, Java language is simple
because: syntax is based on C++ (so easier
for programmers to learn it after C++).
 Removed many confusing and/or rarely-
used features e.g., explicit pointers, operator
overloading etc.
 No need to remove unreferenced objects
because there is Automatic Garbage
Collection in java.
 Object-oriented means we organize our software
as a combination of different types of objects
that incorporates both data and behaviour.
 Object-oriented programming(OOPs) is a
methodology that simplify software development
and maintenance by providing some rules.
 Basic concepts of OOPs are:
 Object
 Class
 Inheritance
 Polymorphism
 Abstraction
 Encapsulation
 A platform is the hardware or software
environment in which a program runs.
 Java code can be run on multiple platforms
e.g. Windows, Linux, Sun Solaris, Mac/OS etc.
 Java code is compiled by the compiler and
converted into bytecode.
 This bytecode is a platform independent code
because it can be run on multiple platforms
 i.e. Write Once and Run Anywhere(WORA).
 Java is secured because: No explicit pointer Programs
run inside virtual machine sandbox.
 Classloader- adds security by separating the package
for the classes of the local file system from those
that are imported from network sources.
 Bytecode Verifier- checks the code fragments for
illegal code that can violate access right to objects.
 Security Manager- determines what resources a class
can access such as reading and writing to the local
disk.
 These security are provided by java language.
 Some security can also be provided by application
developer through SSL,JAAS,cryptography etc.
 Robust simply means strong.
 Java uses strong memory management.
 There are lack of pointers that avoids security
problem.
 There is automatic garbage collection in java.
 There is exception handling and type
checking mechanism in java.
 All these points makes java robust.
 compile time error checking and runtime
checking.
 There is no implementation dependent
features e.g. size of primitive types is set.
 Java compiler generates an architecture-
neutral object file format which makes the
compiled code to be executable on many
processors, with the presence of Java runtime
system.
High-performance
 Java is faster than traditional interpretation
since byte code is "close" to native code still
somewhat slower than a compiled language
(e.g., C++)
Portable
 We may carry the java bytecode to any
platform.
 We can create distributed applications in java.
 RMI and EJB are used for creating distributed
applications.
 We may access files by calling the methods
from any machine on the internet.
 A thread is like a separate program,
executing concurrently.
 We can write Java programs that deal with
many tasks at once by defining multiple
threads.
 The main advantage of multi-threading is
that it shares the same memory.
 Threads are important for multi-media, Web
applications etc.
2. The Java Programming Environment
3. Fundamental Programming Structures in
Java
 To create a simple java program, you need to
create a class that contains main method.
For executing any java program, you need to:
 install the JDK.
 set path of the jdk/bin directory.
 create the java program
 compile and run the java program
 The path is required to be set for using tools
such as javac, java etc.
 If you are saving the java source file inside the
jdk/bin directory, path is not required to be set
because all the tools will be available in the
current directory.
 But If you are having your java file outside the
jdk/bin folder, it is necessary to set path of JDK.
There are 2 ways to set java path:
 temporary
 permanent
To set the temporary path of JDK, you need to
follow following steps:
 Open command prompt
 copy the path of jdk/bin directory
 write in command prompt: set
path=copied_path
 For Example:
setpath=C:Program
FilesJavajdk1.7.0_67bin
 For setting the permanent path of JDK, you
need to follow these steps:
 Go to MyComputer properties -> advanced
tab -> environment variables -> new tab of
user variable -> write path in variable name -
> write path of bin folder in variable value ->
ok -> ok -> ok
 Now your permanent path is set. You can now
execute any program of java from any drive.
class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
}
}
_____________________________________
save this file as Simple.java
______________________________________
To compile:javac Simple.java
To execute:java Simple
______________________________________
Output:Hello Java
 Let's see what is the meaning of class, public,
static, void, main, String[],
System.out.println().
 class keyword is used to declare a class in
java.
 public keyword is an access modifier which
represents visibility, it means it is visible to
all.
 static is a keyword, if we declare any method as
static, it is known as static method. The core
advantage of static method is that there is no
need to create object to invoke the static method.
The main method is executed by the JVM, so it
doesn't require to create object to invoke the
main method. So it saves memory.
 void is the return type of the method, it means it
doesn't return any value.
 main represents startup of the program.
 String[] args is used for command line argument.
We will learn it later.
 System.out.println() is used print statement. We
will learn about the internal working of
System.out.println statement later.
 To write the simple program, open notepad
by start menu -> All Programs ->
Accessories -> notepad and write simple
program as displayed below:
 As displayed in the above diagram, write the
simple program of java in notepad and saved
it as Simple.java. To compile and run this
program, you need to open command prompt
by start menu -> All Programs ->
Accessories -> command prompt.
 To compile and run the above program, go to
your current directory first; my current
directory is c:new .
 Write here:
 To compile:javac Simple.java
 To execute:java Simple
 There are many ways to write a java program.
The modifications that can be done in a java
program are given below:
1) By changing sequence of the modifiers,
method prototype is not changed.
 Let's see the simple code of main method.
 static public void main(String args[])
2) subscript notation in java array can be used
after type, before variable or after variable.
 Let's see the different codes to write the main
method.
 public static void main(String[] args)
 public static void main(String []args)
 public static void main(String args[])
3) You can provide var-args support to main
method by passing 3 ellipses (dots)
 Let's see the simple code of using var-args in
main method. We will learn about var-args
later in Java New Features chapter.
 public static void main(String... args)
4) Having semicolon at the end of class in java
is optional.
Let's see the simple code.
class A{
static public void main(String... args){
System.out.println("hello java4");
}
};
 public static void main(String[] args)
 public static void main(String []args)
 public static void main(String args[])
 public static void main(String... args)
 static public void main(String[] args)
 public static final void main(String[] args)
 final public static void main(String[] args)
 final strictfp public static void main(String[] ar
gs)
 public void main(String[] args)
 static void main(String[] args)
 public void static main(String[] args)
 abstract public static void main(String[] args)
Resolving an error "javac is not recognized as
an internal or external command" ?
 If there occurs a problem like displayed in the
below figure, you need to set path.
 Since DOS doesn't know javac or java, we
need to set path.
 Path is not required in such a case if you
save your program inside the jdk/bin folder.
But its good approach to set path.
 what happens while compiling and running
the java program.
 What happens at compile time?
 At compile time, java file is compiled by Java
Compiler (It does not interact with OS) and
converts the java code into bytecode.
 Classloader: is the subsystem of JVM that is
used to load class files.
 Bytecode Verifier: checks the code fragments
for illegal code that can violate access right to
objects.
 Interpreter: read bytecode stream then
execute the instructions.
Q. Can you save a java source file by other
name than the class name?
ANS: Yes, if the class is not public.
It is explained in the figure given below:
 To compile:javac Hard.java
 To execute:java Simple
Q) Can you have multiple classes in a java
source file?
 Yes, like the figure given below illustrates:
 JVM (Java Virtual Machine) is an abstract machine.
It is a specification that provides runtime
environment in which java bytecode can be
executed.
 JVMs are available for many hardware and
software platforms.
 JVM, JRE and JDK are platform dependent because
configuration of each OS differs.
 But, Java is platform independent.
 The JVM performs following main tasks:
 Loads code
 Verifies code
 Executes code
 Provides runtime environment
 JRE is an acronym for Java Runtime
Environment.
 It is used to provide runtime environment.
 It is the implementation of JVM.
 It physically exists.
 It contains set of libraries + other files that
JVM uses at runtime.
 Implementation of JVMs are also actively
released by other companies besides Sun
Micro Systems.
 JDK is an acronym for Java Development Kit.
 It physically exists.
 It contains JRE + development tools.
 java: Serves as a java interpreter used to run
java applets and applications by reading and
interpreting bytecode.
 javac: servers as java compiler used to
translate java source code to bytecode files.
 javadoc: Creates HTML documentation for
java source files.
 javap: java is disassembler used to convert
bytecode files into java program description.
 jdb: java debugger used to find errors in java
program.
 appletviewer: facilities to run java applet.
 jar: contains package related libraries into a
single executable java archive file(JAR).
The JVM performs following operation:
 Loads code
 Verifies code
 Executes code
 Provides runtime environment
JVM provides definitions for the:
 Memory area
 Class file format
 Register set
 Garbage-collected heap
 Fatal error reporting etc.
 It is a collection of classes, interfaces and
methods which are provide in the form of
java package.
 It is a large already created classes ,
interfaces and methods which provides many
useful capabilities like, GUI, Date, time
,calender.
 java.lang: provides classes that are fundamental
to the design for java programming language.
 java.util: provides legacy collection classes, event
model, collection framework, date and time
capabilites, etc,
 java.io: provides classes for system input and
output through data streams, serialization and
the file system.
 java.awt: classes to create user interface and
painting graphics images.
 java.applet: provids classes necessary to create
applet and used to communicate with its applet
contex.
 java.net:Provides classes that are used to
implement networking in java programs.
1.The Java Platform, Standard Edition(Java SE):
 Helps to develop desktop and console based
applications.
 Most commonly used.
 Contains java API, run time environment.
2. The Java Platform, Enterprise Edition(Java
EE): Helps to build server-side applications.
3. The Java Platform, Micro Edition(Java
ME):Helps to build java application for micro
devices, which includes hand-held devices
like, mobile phone, PDA’s etc.
 Variable is a name of memory location.
 Variables are nothing but reserved memory
locations to store values.
 This means that when you create a variable you
reserve some space in memory.
 Based on the data type of a variable, the operating
system allocates memory and decides what can be
stored in the reserved memory.
 Therefore, by assigning different data types to
variables, you can store integers, decimals, or
characters in these variables.
24-12-2014, 4:15 to 5:15
Variable
 Variable is name of reserved area allocated in
memory.
 int data=10;//Here data is variable
There are three types of variables:
 Local
 instance
 static.
There are two data types available in Java:
 Primitive Data Types
 Reference/Object Data Types(and non-
primitive)
There are three types of variables in java
 Local variable
 instance variable
 static variable
 Local variables are declared in methods,
constructors, or blocks.
 Local variables are created when the method,
constructor or block is entered and the
variable will be destroyed once it exits the
method, constructor or block.
 Access modifiers cannot be used for local
variables.
 Local variables are visible only within the
declared method, constructor or block.
 There is no default value for local variables so
local variables should be declared and an
initial value should be assigned before the
first use.
 Instance variables are declared in a class, but
outside a method, constructor or any block.
 Instance variables are created when an object
is created with the use of the keyword 'new'
and destroyed when the object is destroyed.
 Access modifiers can be given for instance
variables
 The instance variables are visible for all
methods, constructors and block in the class.
Normally, it is recommended to make these
variables private (access level).
 Instance variables have default values.
 “Class variables” are also known as static
variables
 Are declared with the static keyword in a class,
but outside a method, constructor or a block.
 There would only be one copy of each class
variable per class, regardless of how many
objects are created from it.
 Static variables are stored in static memory.
 Static variables are created when the program
starts and destroyed when the program stops.
class A{
int data=50;//instance variable
static int m=100;//static variable
void method(){
int n=90;//local variable
}
}//end of class
Every variable in JAVA has a data type.
Data types specify the size and type of values that
can be stored.
 Primitive types are also known as simple data
types•
 A primitive type is predefined by the
language•
 Non-primitive types are also known as
reference types•
Non-primitive types are :
 Classes
 Interfaces
 Arrays
 Java defines four integer types: byte, short,
int and long.
 All these are signed, positive and negative
values•
 Java does not support unsigned types•
 byte is 8 bit width , short is 16 bit width
int is 32 bit width and long is 64 bit width.
 The smallest integer type is byte •
 Range from -128 to +127•
 Byte variables are declared by use of keyword
‘byte ‘
 Variables of type byte are especially useful
when you’re working with a stream of data
from a network or file.
 eg.
byte x, y;
 Short is a signed 16-bit type.
 It has a range from –32,768 to 32,767.
 It is probably the least-used Java type.
 Here are some examples of short variable
declarations:
short s;
short t;
 The most commonly used integer type is int.
 It is a signed 32-bit type
 Range from –2,147,483,648 to
2,147,483,647.
 In addition to other uses, variables of type
int are commonly employed to control loops
and to index arrays.
 e.g:
int x;
 long is a signed 64 bit type•
 Useful where an int type is not large enough
to hold the desired value•
 The range of large is quite large•
 This makes it useful when large, whole
numbers are needed•
 Keyword used is ‘long’
 eg. : long seconds;
// Compute distance light travels using long variables.
class Light {
public static void main(String args[]) {
int lightspeed;
long days;
long seconds;
long distance;
// approximate speed of light in miles per second
lightspeed = 186000;
days = 1000; // specify number of days here
seconds = days * 24 * 60 * 60; // convert to seconds
distance = lightspeed * seconds; // compute distance
System.out.print("In " + days);
System.out.print(" days light will travel about ");
System.out.println(distance + " miles.");
}
}
output:
In 1000 days light will travel about 16070400000000 miles.
 floating point numbers are also known as
real numbers•
 Are used when fractional components are
required•
 float and double are two kinds of floating
point types•
 Keywords used are ‘float’ and ‘double’
 float specify a single precision value that uses
32 bits of storage•
 float type is useful when you require
fractional component to save.
 eg.
float area;
float hightemp, lowtemp;
 Double precision, as denoted by the double
keyword, uses 64 bits to store a value.
Double
 Double precision is actually faster than single
precision on some modern processors that
have been
 optimized for high-speed mathematical
calculations.
// Compute the area of a circle.
class Area {
public static void main(String args[]) {
double pi, r, a;
r = 10.8; // radius of circle
pi = 3.1416; // pi, approximately
a = pi * r * r; // compute area
System.out.println("Area of circle is " + a);
}
}
Output:Area of circle is 366.436224
 In Java the data type used to store character
is char•
 char in Java is different from char in C and
C++•
 Java used Unicode to represent characters•
 Java character is 16 bit type.
 The range of the characters is 0 to 65,536
// Demonstrate char data type.
class CharDemo {
public static void main(String args[]) {
char ch1, ch2;
ch1 = 88; // code for X
ch2 = 'Y';
System.out.print("ch1 and ch2: ");
System.out.println(ch1 + " " + ch2);
}
}
Output:ch1 and ch2: X Y
// char variables behave like integers.
class CharDemo2 {
public static void main(String args[]) {
char ch1;
ch1 = 'X';
System.out.println("ch1 contains " + ch1);
ch1++; // increment ch1
System.out.println("ch1 is now " + ch1);
}
}
Output:
ch1 contains X
ch1 is now Y
 boolean data type is used to represent
logical values that can be either true or false•
 All relational, conditional and logical
operators return boolean values•
 It used only one bit of storage•
 Keyword used is ‘boolean’•
 eg;. boolean flag;
 byte----- 0
 short----- 0
 int---- 0
 long---- 0L
 float-------0.0f
 double------0.0d
 char--------’u000’
 boolean ----- false
 Variables are container or placeholder, since
the values stored in them can be changed
during the execution.
 You must declare a variable before using it in
a program.
 Syntax:
dataType variable;//declaring variable
 dataType specifies valid dataType like int,
float etc
 Variables can be any name.
 Can declare more than one variable:
dataType variable1,variable2,...variableN;
 After declaration, can assign value to the
variable.
 Assigning value to the variable ,know as a
initializing variables.
 dataType variable=val;
OR
 dataType variable;
-----
-----
variable=val;
 int a, b, c; // declares three ints, a, b, and c.
 int d = 3, e, f = 5; // declares three more
ints, initializing d and f.
 byte z = 22; // initializes z.
 double pi = 3.14159; // declares an
approximation of pi.
 char x = 'x'; // the variable x has the value 'x'
 Type casting is the process of converting an
entity of one data type into another data type.
 If the two types are compatible, then Java will
perform the conversion automatically.
 For example, it is always possible to assign an int
value to a long variable.
 However, not all types are compatible, and thus,
not all type conversions are implicitly allowed.
 For instance, there is no automatic conversion
defined from double to byte.
 It is still possible to obtain a conversion between
incompatible types
 26-12-2014, 5 :15 -6:15
 Following are the two ways of conversions
included in typecasting:
1. Automatic Type Casting
2. Casting Incompatible Data Types.
 When one type of data is assigned to another
type of variable, an automatic type conversion
will take place.
 Two data type being used must be compatible
with each other.
 The destination type is larger than the source
type.
 Numeric data types, such as int and float are
compatible to each other.
 Where as int, float is not compatible with boolean
and char data types.
 “widening conversion” takes place here.
class AutoCastDemo {
public static void main(String[] args) {
int i= 150;
long l;
l=i;
System.out.println("The value of Long variable is::"+
l);
}
}
Output: The value of Long variable is::150
 When you assign large data value to a variable of
data type that cant not hold the assigned value,
then need explicit type casting:
Target_Variable=(target_data_type)
Source_Variable;
 Target_Variable=in which data is to be assigned.
 target_data_type= is the data type of the
Target_Variable.
 Source_Variable=variable whose value is being
assigned to Target_Variable.
public class ExplicitCastDemo {
public static void main(String[] args) {
int i;
long l=200;
i=(int)l;
System.out.println("The value of INT
variable is::"+ i);
}
}
output:The value of INT variable is::200
Rules:
 All byte, short, and char values are promoted
to int.
 Then, if one operand is a long, the whole
expression is promoted to long.
 If one operand is a float, the entire
expression is promoted to float.
 If any of the operands is double, the result is
double.
class Promote {
public static void main(String args[]) {
byte b = 42;
char c = 'a';
short s = 1024;
int i = 50000;
float f = 5.67f;
double d = .1234;
double result = (f * b) + (i / c) - (d * s);
System.out.println((f * b) + " + " + (i / c) + " - " +
(d * s));
System.out.println("result = " + result);
}
}
 Type promotions that occur in this line from
the program:
double result = (f * b) + (i / c) - (d * s);
=(float+int)-double
=float-double
=double
 f * b, b is promoted to a float and the result
of the subexpression is float.
 the subexpression i/c, c is promoted to int
and the result is of type int.
 In d*s, the value of s is promoted to double,
and the type of the subexpression is double.
 Finally, these three intermediate values float,
int and double are considered.
 The outcome of float plus an int is a float.
 Then the resultant float minus the last double
is promoted to double,
 which is the type for the final result of the
expression.
 After declaring variable as a final, you can not
assign any other value to that variable.
 In C and C++ constants defined using
#define statements.
 In java constants are used by keyword final.
 final variable should be declare at the
beginning of the class as a class member and
not within a method.
 final double pi=3.14;
 Literal in Java refer to fixed values that do not
change during the execution of the program•
 Java supports several types of constants •
1. Integer Literal •
2. Real Literal (Floating -point)•
3. Character Literal •
4. Boolean Literal.
5. String Literal •
 An integer literal refers to sequence of digits•
Integers are of three types• They are •
1. Decimal Integer
2. Octal Integer
3. Hexadecimal Integer
Decimal Integer:
 Decimal Integers consists of a set of digits
from 0 to 9,preceeded by an optional minus(-
) sign
 Used as base 10.
 eg. : +999,-999•
 Embedded spaces ,commas and non-digit
characters are not permitted in between
digits
 eg. 99 999, 99,999 , $999 are illegal
numbers.
//Program for Decimal literals
public class DecimalLit {
public static void main(String[] args) {
int sixteen=16;
System.out.println("Decimal
Sixteen="+sixteen);
}
}
//Output: Decimal Sixteen=16
Octal Integer:
 Base of octal number system is 8.
 Digits from 0-7 are same as decimal number
system.
 Number 8 of decimal number system is
represented by 10, 9 by 11 and so on.
 An octal integer consists of any combination
of digits from 0 to 7 with a leading zero(0)
eg. 045,063,026
//Program for octal literals
public class OctalLit {
public static void main(String[] args) {
int five=05; //Value of five is equal to decimal 5
int eight=010; //Value of eight is equal to decimal 8
int ten=012; //Value of ten is equal to decimal 10
System.out.println("Octal value of 012 is equivalent
to::"+ten+"in decimal");
}
}
//Output: Octal value of 012 is equivalent to::10 in
decimal
Hexa Decimal Integer:
 A sequence of digits preceded by 0x or 0X is
considered as hexa decimal integers•
 They may also include alphabets from A to F
or a to f•
 Letters from a to f represents the numbers
from 10 to 15
 eg. 0xd,0XF etc.,
 Base 16.
//Program for Hexadecimal literal
public class HexadecimalLit {
public static void main(String[] args) {
int a=0x5; //value of a is equvalent to decimal 5
int b=0xF; //value of b is equvalent to decimal 15
int c= 0Xd; //value of c is equvalent to decimal 13
System.out.println("Decimal five::"+a);
System.out.println("Decimal fifteen::"+b);
System.out.println("Decimal thirteen::"+c);
}
}
/*Output::
Decimal five::5
Decimal fifteen::15
Decimal thirteen::13 */
Real Literals:
 Numbers containing fractional parts are
called real literals/ Floating-point literals.
 eg. 9.999,0.999 etc.,•
 Floating-point numbers are like real numbers
in mathematics,
 for example, 4.13179, -0.000001.
 Java has two kinds of floating-point numbers:
float and double.
 float temp=7.86f// correct
 float hight=6.45;//generate an error;
 double distance=67.895432d;//correct
 double distance1=876.9876;//correct
 The default type when you write a floating-
point literal is double, but you can designate
it explicitly by appending the D (or d) suffix.
 However, the suffix F (or f) is appended to
designate the data type of a floating-point
literal as float.
 We can also specify a floating-point literal in
scientific notation using Exponent (short E or
e).
 Examples include 6.022E23,
and 2e+100.
class FloatingPointLit{
public static void main(String args[]){
float hight=6.45f;
System.out.println("Hight::"+hight);
}
}
//Output: Hight::6.45
 char data type is a single 16-bit Unicode
character.
 single printable character literal denotes in a
pair of single quote characters such as 'a', '#',
and '3'.
 You must know about the ASCII character set.
 The ASCII character set includes 128 characters
including letters, numerals, punctuation etc..
 char letter=‘A’;
 char value=‘Y’;
 char newline=‘n’;
 char character j=‘u004A’;
String Literals:
 A String Literal is a sequence of characters
enclosed between double quote marks “ “
 The characters may be alphabets, digits,
special characters and blank spaces
 eg. “SGGSIE & T”
 String is considered as a class insteated of
primitive data type.
 As Sting literals are converted by the compiler
into string objects,
 The values true and false are treated as literals in Java
programming.
 When we assign a value to a boolean variable, we can
only use these two values.
 Unlike C, we can't presume that the value of 1 is
equivalent to true and 0 is equivalent to false in Java.
 We have to use the values true and false to represent
a Boolean value.
Example
boolean chosen = true; //correct
Boolean temp=1;// Generate an error
 Remember that the literal true is not represented by
the quotation marks around it.
 The Java compiler will take it as a string of characters,
if its in quotation marks.
 An operator is a symbol that allows a
programmer to perform certain arithmetic
and logical operations on data and variables.
 There are different types of operators
available in Java:
1. Arithmetic
2. Increment and Decrement
3. Relational
4. Logical
5. Bitwise
6. Conditional
7. Special(instanceOf and dot)
 Arithmetic operators are used in mathematical
expressions.
//Performing Addition and Subtraction on double data type
variables
public class IntAddSub {
public static void main(String[] args) {
double a=50.5;
double b=30.4;
System.out.println("First number is:"+a);
System.out.println("Second number is:"+b);
double c=a+b;
System.out.println("Addition of two number is:"+c);
c=a-b;
System.out.println("Sustraction of two number is:"+c);
}
}
/*OUTPUT:First number is:50.5
Second number is:30.4
Addition of two number is:80.9
Sustraction of two number is:20.1*/
The Modulus Operator
 The modulus operator,%, returns the
remainder of a division operation.
 It can be applied to floating-point types as
well as integer types.
// Demonstrate the % operator.
class Modulus {
public static void main(String args[]) {
int x = 42;
double y = 42.25;
System.out.println("x mod 10 = " + x % 10);
System.out.println("y mod 10 = " + y % 10);
}
}
output:
x mod 10 = 2
y mod 10 = 2.25
Arithmetic Compound Assignment Operators:
 Java provides special operators that can be
used to combine an arithmetic operation with
an assignment.
 Common Programming:
a = a + 4;
 In Java, you can rewrite this statement as
shown here:
a += 4;
 This version uses the+=compound
assignment operator.
 Both statements perform the same
action: they increase the value of a by 4.
// Demonstrate several assignment operators.
class OpEquals {
public static void main(String args[]) {
int a = 1;
int b = 2;
int c = 3;
a += 5; //a=a+5;
b *= 4;
c += a * b;
c %= 6;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
}
}
The output of this program is shown here:
a = 6
b = 8
c = 3
 ++ and the - - are Java's increment and
decrement operators.
 The increment operator increases its operand by
one.
 x++; is equivalent to x = x + 1;
 The decrement operator decreases its operand
by one.
 y--; is equivalent to y = y – 1;
 They can appear both in
• postfix form, where they follow the operand, and
• prefix form, where they precede the operand.
 Prefix: The value of the operand is incremented
and decremented before assigning it to the
another variable.
 Example:
x = 19; y = ++x;
Output: y = 20 and x = 20
 Postfix: The value of the operand is incremented
or decremented after assigning it to another
variable.
 Example:
x = 19; y = x++;
Output: y = 19 and x = 20
 A relational operator compares two values
and determines the relationship between
them.
 For example, != returns true if its two
operands are unequal.
 Relational operators are used to test whether
two values are equal, whether one value is
greater than another, and so forth.
public LessThanExample
{
publi cstatic void main(String args[])
{
int a = 5; int b = 10;
if(a < b)
{
System.out.println("a is less than b");
}
}
}
 The Boolean logical operators shown here
operate only on boolean operands.
 All of the binary logical operators combine
two boolean values to form resultant boolean
value.
public class Test {
public static void main(String args[]) {
int a = 10;
int b = 20;
System.out.println("a == b = " + (a == b) );
System.out.println("a != b = " + (a != b) );
System.out.println("a > b = " + (a > b) );
System.out.println("a < b = " + (a < b) );
System.out.println("b >= a = " + (b >= a) );
System.out.println("b <= a = " + (b <= a) );
}
}
 This would produce the following result:
a == b = false
a != b = true
a > b = false
a < b = true
b >= a = true
b <= a = false
 Java defines several bitwise operators that
can be applied to the integer types, long, int,
short, char and byte.
 These operators act upon the individual bits(0
and 1) of their operands.
Bitwise Logical Operators :
 The bitwise logical operators are •
1. ~ (NOT)
2. & (AND)
3. | (OR)
4. ^ (XOR)
The Left Shift
 The left shift operator,<<, shifts all of the
bits in a value to the left a specified number
of times.
value << num
Example:
01000001 65
<< 2
00000100
The Right Shift
 The right shift operator, >>, shifts all of the bits
in a value to the right a specified number of
times.
value >> num
Example:
00100011 35
>> 2
00001000
 When we are shifting right, the top (leftmost) bits
exposed by the right shift are filled in with the
previous contents of the top bit.
 This is called sign extension and serves to
preserve the sign of negative numbers when you
shift them right.
The Unsigned Right Shift •
 In these cases, to shift a zero into the high-
order bit no matter what its initial value was.
This is known as an unsigned shift.
 To accomplish this, we will use Java’s
unsigned, shift-right operator, >>>, which
always shifts zeros into the high-order bit.
 Example:
11111111 11111111 11111111 11111111
–1 in binary as an int
>>>24
00000000 00000000 00000000 11111111
255 in binary as an int
 combines the assignment with the bitwise
operation.
 Similar to the algebraic operators
 For example, the following two statements,
which shift the value in a right by four bits,
are equivalent:
a = a >> 4;
a >>= 4;
 Likewise,
a = a | b;
a |= b;
 Java includes a special ternary (three-
way)operator, ?, that can replace certain types of
if-then-else statements.
 The ? has this general form:
expression1 ? expression2 : expression3
 Here,expression1 can be any expression that
evaluates to a boolean value.
 If expression1 is true , then expression2 is
evaluated; otherwise, expression3 is evaluated.
 The result of the? operation is that of the
expression evaluated.
 Both expression2 and expression3 are required
to return the same type, which can’t be void.
 Example: TestTernary.java
 ratio = denom == 0 ? 0 : num / denom;
 When Java evaluates this assignment
expression, it first looks at the expression to
the left of the question mark.
 If denom equals zero, then the expression
between the question mark and the colon is
evaluated and used as the value of the entire
? expression.
 If denom does not equal zero, then the
expression after the colon is evaluated and
used for the value of the entire ? expression.
•The result produced by the? operator is then
assigned to ratio.
public class Test {
public static void main(String args[]){
int a , b;
a = 10;
b = (a == 1) ? 20: 30;
System.out.println( "Value of b is : " + b );
b = (a == 10) ? 20: 30;
System.out.println( "Value of b is : " + b );
}
}
This would produce the following result:
Value of b is : 30
Value of b is : 20
 This operator is used only for object
reference variables.
 The operator checks whether the object is of
a particular type(class type or interface type).
instanceof operator is written as:
( Object reference variable ) instanceof
(class/interface type)
 If the object referred by the variable on the
left side of the operator passes the IS-A
check for the class/interface type on the right
side, then the result will be true.
public class Test {
public static void main(String args[]){
String name = "James";
// following will return true since name is
type of String
boolean result = name instanceof String;
System.out.println( result );
}
}
This would produce the following result:
true
class Vehicle {}
public class Car extends Vehicle {
public static void main(String args[]){
Vehicle a = new Car();
boolean result = a instanceof Car;
System.out.println( result );
}
}
This would produce the following result:
true
Operator Precedence :
 Java provides a data structure, the array.
 which stores a fixed-size sequential collection
of elements of the same type.
 Array in java is index based, first element of the
array is stored at 0 index & last at n-1th index.
Advantage of Java Array
 Code Optimization: It makes the code
optimized, we can retrieve or sort the data
easily.
 Random access: We can get any data located
at any index position.
Disadvantage of Java Array
 Size Limit: We can store only fixed size of
elements in the array.
 It doesn't grow its size at runtime.
 To solve this problem, collection framework is
used in java.
There are two types of array.
1. Single Dimensional Array
1. Multidimensional Array
data_type var_name[ ];
 data_type=data type of the array.
 var_name= is the name of the array.
Ex:
int roll_no [ ];
int [ ] tele_no;
 You can create an array by using the new
operator with the following syntax:
var_name=new data_type [size];
 var_name= name of the array declared.
 New is the keyword, which is used to allocate
memory fo the var_name array.
 data_type= Data type of the element stored in
the array.
 size=Total number of elements that will be
stored in array.
roll_no=new int[10];
Total number of element stored=10
Memory allocated=40 bytes(10*4)
 Array declaration and creation in a single
step:
int roll_no [ ]= new int[10];
Initializing array:
roll_no [0]=121;
roll_no [1]=122;
roll_no [2]=123;
roll_no [3]=124;
roll_no [4]=125;
roll_no [5]=126;
........
roll_no [9]=130;
 Can initialize at the time of declaration, then there
is no need:
 To use new keyword to assign memory.
 No need to specify size of an array.
int roll_no [
]={121,122,123,124,125,126,127,128,129,130};
public class ArrayEx1 {
public static void main(String[] args) {
int x;
int even[];
even= new int[5];
even [0]=20;
even [1]=12;
even [2]=3;
even [3]=124;
even [4]=10;
for(x=0;x<even.length;x++){
if(even[x]%2==0){
}
System.out.println(even[x]+"is an even number");
}
}
}
 op:
20is an even number
12is an even number
124is an even number
10is an even number
class TestArrayCopyDemo {
public static void main(String[] args) {
char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f',
'e‘,‘i', 'n', 'a', 't', 'e', 'd' };
char[] copyTo = new char[7];
System.arraycopy(copyFrom, 2, copyTo, 0, 7);
System.out.println(new String(copyTo));
}
}
op:
caffein
class Testarray2{
static void min(int arr[]){
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];
System.out.println(min);
}
public static void main(String args[]){
int a[]={33,3,4,5};
min(a);//passing array to method
}}
op: 3
 Data is stored in row and column based
index (also known as matrix form).
 dataType arrayRefVar[][];
 dataType[][] arrayRefVar; (or)
 dataType [][]arrayRefVar; (or)
instantiate Multidimensional Array
int[][] arr=new int[3][3];//3 row and 3 column
 arr[0][0]=1;
 arr[0][1]=2;
 arr[0][2]=3;
 arr[1][0]=4;
 arr[1][1]=5;
 arr[1][2]=6;
 arr[2][0]=7;
 arr[2][1]=8;
 arr[2][2]=9;
 int arr[] []=new int [4][3];
 arr.length=4
 arr[i].lengt= 3
_______________________________________
for(i=0;i<arr.length;i++)
for(j=0;j<arr[i].lenght;j++)
arr[i][j]=Integer.parseInt(obj.readLine());
class Testarray3{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}}
1 2 3
2 4 5
4 4 5
int arr[i][j][k]=new int[2][4][5];
arr.length= 2(No. Of 2-D array)
arr[i].length= 4
arr[i][j].length=5
 __________________________________
for(i=0;i<arr.length;i++)
for(j=0;j<arr[i].length;j++)
for(k=0;k<arr[i][j].length;k++)
arr[i][j][k]=obj.nextInt();
 More than one statement in the initialization and iteration
portions of the for loop can be used.
 Example 1:
class var2 {
public static void main(String arr[])
{
int a, b;
b = 5;
for(a=0; a<b; a++) {
System.out.println("a = " + a);
System.out.println("b = " + b);
b--;
}
}
}
 o/p:
a = 0
b = 5
a = 1
b = 4
a = 2
b = 3
 Example 2:
class var2 {
public static void main(String arr[]) {
int x, y;
for(x=0, y=5; x<=y; x++, y--) {
System.out.println("x= " + x);
System.out.println("y="+y);}
}}
op:
x= 0
y=5
x= 1
y=4
x= 2
y=3
 Beginning with JDK 5, a second form of for
was defined that implements a “for-each”
style loop.
 For-each is also referred to as the enhanced
for loop.
 Specifically designed for collections.
 For-each loop repeatedly executes a group of
statements for each element of the collection.
 Executes as may times as the number of
elements in collection.
 Array is a type of a collection.
for(var:collection)
{
Statements;
}
class var2
public static void main(String arg[]) {
int arr[]={1,3,5,7,11,13,15,17,19};
System.out.println("First 10 odd numbers
are:");
for(int i:arr){
System.out.println(i);
}
}
}
 There are various ways to read input from the
keyboard, the java.util.Scanner class is one of
them.
 Scanner class is one of the class of Java which
provides the methods to get inputs.
 Scanner class is present in java.util package
so we import this package in our program.
 We first create an object of Scanner class and
then we use the methods of Scanner class.
 Scanner a = new Scanner(System.in);
Following are methods of Scanner class:
 next( ) :to input a string
 nextByte() :to input a byte value
 nextInt( ) :to input an integer
 nextFloat( ) :to input a float
 nextLong( ) :for Long Values
 nextDouble() :for double values
import java.util.*;
public class InputTest
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
// get first input
System.out.print("What is your name? :");
String name = in.nextLine();
// get second input
System.out.print("How old are you? :");
int age = in.nextInt();
// display output on console
System.out.println("Hello, " + name + ". Next year, you'll be
" + (age + 1));
}
}
 // System.out.println("We will not use
'Hello, World!'"); // is this too cute?
 /*....*/ you can use the /*and */comment
delimiters that let you block off a longer
comment.
 /****........*/
used to generate documentation
automatically. This comment uses a /**to
start and a */to end.
 Java naming convention is a rule to follow as you
decide what to name your identifiers such as
class, package, variable, constant, method etc.
 But, it is not forced to follow. So, it is known as
convention not rule.
 By using standard Java naming conventions, you
make your code easier to read for yourself and
for other programmers.
 Readability of Java program is very important. It
indicates that less time is spent to figure out
what the code does.
1.introduction to java

More Related Content

What's hot

Introduction to java
Introduction to javaIntroduction to java
Introduction to java
Ajay Sharma
 
Chapter 1
Chapter 1Chapter 1
Chapter 1
siragezeynu
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
jayc8586
 
basic core java up to operator
basic core java up to operatorbasic core java up to operator
basic core java up to operator
kamal kotecha
 
1 java programming- introduction
1  java programming- introduction1  java programming- introduction
1 java programming- introduction
jyoti_lakhani
 
Core Java
Core JavaCore Java
Core Java
Prakash Dimmita
 
Introduction to JAVA
Introduction to JAVAIntroduction to JAVA
Introduction to JAVA
Mindsmapped Consulting
 
Core Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsCore Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika Tutorials
Mahika Tutorials
 
Introduction to Java Programming
Introduction to Java ProgrammingIntroduction to Java Programming
Introduction to Java Programming
Ravi Kant Sahu
 
Java basic introduction
Java basic introductionJava basic introduction
Java basic introduction
Ideal Eyes Business College
 
Java basic
Java basicJava basic
Java basic
Arati Gadgil
 
Java features
Java featuresJava features
Java features
Prashant Gajendra
 
Fundamentals of JAVA
Fundamentals of JAVAFundamentals of JAVA
Fundamentals of JAVA
KUNAL GADHIA
 
Java basics
Java basicsJava basics
Java basics
suraj pandey
 
Java Programming
Java ProgrammingJava Programming
Java Programming
Elizabeth alexander
 
Core java course syllabus
Core java course syllabusCore java course syllabus
Core java course syllabus
Papitha Velumani
 
Basics of JAVA programming
Basics of JAVA programmingBasics of JAVA programming
Basics of JAVA programming
Elizabeth Thomas
 

What's hot (20)

Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Chapter 1
Chapter 1Chapter 1
Chapter 1
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
basic core java up to operator
basic core java up to operatorbasic core java up to operator
basic core java up to operator
 
Core java slides
Core java slidesCore java slides
Core java slides
 
1 java programming- introduction
1  java programming- introduction1  java programming- introduction
1 java programming- introduction
 
Programming in Java
Programming in JavaProgramming in Java
Programming in Java
 
Core Java
Core JavaCore Java
Core Java
 
Introduction to JAVA
Introduction to JAVAIntroduction to JAVA
Introduction to JAVA
 
Java essential notes
Java essential notesJava essential notes
Java essential notes
 
Core Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsCore Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika Tutorials
 
Introduction to Java Programming
Introduction to Java ProgrammingIntroduction to Java Programming
Introduction to Java Programming
 
Java basic introduction
Java basic introductionJava basic introduction
Java basic introduction
 
Java basic
Java basicJava basic
Java basic
 
Java features
Java featuresJava features
Java features
 
Fundamentals of JAVA
Fundamentals of JAVAFundamentals of JAVA
Fundamentals of JAVA
 
Java basics
Java basicsJava basics
Java basics
 
Java Programming
Java ProgrammingJava Programming
Java Programming
 
Core java course syllabus
Core java course syllabusCore java course syllabus
Core java course syllabus
 
Basics of JAVA programming
Basics of JAVA programmingBasics of JAVA programming
Basics of JAVA programming
 

Similar to 1.introduction to java

CORE JAVA
CORE JAVACORE JAVA
Java programming material for beginners by Nithin, VVCE, Mysuru
Java programming material for beginners by Nithin, VVCE, MysuruJava programming material for beginners by Nithin, VVCE, Mysuru
Java programming material for beginners by Nithin, VVCE, Mysuru
Nithin Kumar,VVCE, Mysuru
 
Java introduction
Java introductionJava introduction
Java introduction
The icfai university jaipur
 
java basic for begginers
java basic for begginersjava basic for begginers
java basic for begginers
divaskrgupta007
 
JAVA introduction and basic understanding.pptx
JAVA  introduction and basic understanding.pptxJAVA  introduction and basic understanding.pptx
JAVA introduction and basic understanding.pptx
prstsomnath22
 
Java-1st.pptx about Java technology before oops
Java-1st.pptx about Java technology before oopsJava-1st.pptx about Java technology before oops
Java-1st.pptx about Java technology before oops
buvanabala
 
Top 10 Important Core Java Interview questions and answers.pdf
Top 10 Important Core Java Interview questions and answers.pdfTop 10 Important Core Java Interview questions and answers.pdf
Top 10 Important Core Java Interview questions and answers.pdf
Umesh Kumar
 
Introduction java programming
Introduction java programmingIntroduction java programming
Introduction java programming
Nanthini Kempaiyan
 
JAVA ALL 5 MODULE NOTES.pptx
JAVA ALL 5 MODULE NOTES.pptxJAVA ALL 5 MODULE NOTES.pptx
JAVA ALL 5 MODULE NOTES.pptx
DrPreethiD1
 
OOP-Chap2.docx
OOP-Chap2.docxOOP-Chap2.docx
OOP-Chap2.docx
NaorinHalim
 
Lecture - 1 introduction to java
Lecture - 1 introduction to javaLecture - 1 introduction to java
Lecture - 1 introduction to java
manish kumar
 
Sybsc cs sem 3 core java
Sybsc cs sem 3 core javaSybsc cs sem 3 core java
Sybsc cs sem 3 core java
WE-IT TUTORIALS
 
JAVA for Every one
JAVA for Every oneJAVA for Every one
JAVA for Every one
Satyam Pandey
 
Java Programming
Java ProgrammingJava Programming
Java Programming
Prof. Dr. K. Adisesha
 
Chapter 2.1
Chapter 2.1Chapter 2.1
Chapter 2.1sotlsoc
 
JAVA PROGRAMMING-Unit I - Final PPT.pptx
JAVA PROGRAMMING-Unit I - Final PPT.pptxJAVA PROGRAMMING-Unit I - Final PPT.pptx
JAVA PROGRAMMING-Unit I - Final PPT.pptx
SuganthiDPSGRKCW
 
Introduction to Java Programming.pdf
Introduction to Java Programming.pdfIntroduction to Java Programming.pdf
Introduction to Java Programming.pdf
AdiseshaK
 

Similar to 1.introduction to java (20)

CORE JAVA
CORE JAVACORE JAVA
CORE JAVA
 
Java programming material for beginners by Nithin, VVCE, Mysuru
Java programming material for beginners by Nithin, VVCE, MysuruJava programming material for beginners by Nithin, VVCE, Mysuru
Java programming material for beginners by Nithin, VVCE, Mysuru
 
Java introduction
Java introductionJava introduction
Java introduction
 
java basic for begginers
java basic for begginersjava basic for begginers
java basic for begginers
 
JAVA introduction and basic understanding.pptx
JAVA  introduction and basic understanding.pptxJAVA  introduction and basic understanding.pptx
JAVA introduction and basic understanding.pptx
 
Javalecture 1
Javalecture 1Javalecture 1
Javalecture 1
 
UNIT 1.pptx
UNIT 1.pptxUNIT 1.pptx
UNIT 1.pptx
 
Java-1st.pptx about Java technology before oops
Java-1st.pptx about Java technology before oopsJava-1st.pptx about Java technology before oops
Java-1st.pptx about Java technology before oops
 
Top 10 Important Core Java Interview questions and answers.pdf
Top 10 Important Core Java Interview questions and answers.pdfTop 10 Important Core Java Interview questions and answers.pdf
Top 10 Important Core Java Interview questions and answers.pdf
 
Introduction java programming
Introduction java programmingIntroduction java programming
Introduction java programming
 
JAVA ALL 5 MODULE NOTES.pptx
JAVA ALL 5 MODULE NOTES.pptxJAVA ALL 5 MODULE NOTES.pptx
JAVA ALL 5 MODULE NOTES.pptx
 
OOP-Chap2.docx
OOP-Chap2.docxOOP-Chap2.docx
OOP-Chap2.docx
 
Lecture - 1 introduction to java
Lecture - 1 introduction to javaLecture - 1 introduction to java
Lecture - 1 introduction to java
 
Sybsc cs sem 3 core java
Sybsc cs sem 3 core javaSybsc cs sem 3 core java
Sybsc cs sem 3 core java
 
OOPS JAVA.pdf
OOPS JAVA.pdfOOPS JAVA.pdf
OOPS JAVA.pdf
 
JAVA for Every one
JAVA for Every oneJAVA for Every one
JAVA for Every one
 
Java Programming
Java ProgrammingJava Programming
Java Programming
 
Chapter 2.1
Chapter 2.1Chapter 2.1
Chapter 2.1
 
JAVA PROGRAMMING-Unit I - Final PPT.pptx
JAVA PROGRAMMING-Unit I - Final PPT.pptxJAVA PROGRAMMING-Unit I - Final PPT.pptx
JAVA PROGRAMMING-Unit I - Final PPT.pptx
 
Introduction to Java Programming.pdf
Introduction to Java Programming.pdfIntroduction to Java Programming.pdf
Introduction to Java Programming.pdf
 

Recently uploaded

Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024
Sharepoint Designs
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
Cyanic lab
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Globus
 
Advanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowAdvanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should Know
Peter Caitens
 
Why React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdfWhy React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdf
ayushiqss
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
Tendenci - The Open Source AMS (Association Management Software)
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
De mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FMEDe mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FME
Jelle | Nordend
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
Globus
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
Strategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptxStrategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptx
varshanayak241
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
IES VE
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
Globus
 

Recently uploaded (20)

Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
 
Advanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowAdvanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should Know
 
Why React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdfWhy React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdf
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
De mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FMEDe mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FME
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
Strategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptxStrategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptx
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 

1.introduction to java

  • 1.
  • 2.  What is java  History  Java as a Programming Tool  Advantages of Java  The Java “White Paper” Buzzwords  Java and the Internet
  • 3.  Java is a programming language.  It is a platform.  Platform: Any hardware or software environment in which a program runs, is known as a platform.  Since Java has its own runtime environment (JRE) and API, it is called platform.
  • 4.  According to Sun, 3 billion devices run java.  There are many devices where java is currently used. Some of them are as follows:  Desktop Applications such as acrobat reader, media player, antivirus etc.  Web Applications such as irctc.co.in, oracle.com etc.  Enterprise Applications such as banking applications.  Mobile  Embedded System  Smart Card  Robotics  Games etc.
  • 5. There are mainly 4 type of applications that can be created using java: 1) Standalone Application  It is also known as desktop application or window-based application.  An application that we need to install on every machine such as media player, antivirus etc.  AWT and Swing are used in java for creating standalone applications. 2) Web Application  An application that runs on the server side and creates dynamic page, is called web application.  Currently, servlet, jsp, struts, jsf etc. technologies are used for creating web applications in java.
  • 6. 3) Enterprise Application  An application that is distributed in nature, such as banking applications etc.  It has the advantage of high level security, load balancing and clustering.  In java, EJB is used for creating enterprise applications. 4) Mobile Application  An application that is created for mobile devices.  Currently Android and Java ME are used for creating mobile applications.
  • 7.  There is given many features of java.  They are also known as java buzzwords. Simple Object-Oriented Platform independent Secured Robust Architecture neutral Portable Dynamic Multithreaded High Performance Interpreted Distributed
  • 8.  According to Sun, Java language is simple because: syntax is based on C++ (so easier for programmers to learn it after C++).  Removed many confusing and/or rarely- used features e.g., explicit pointers, operator overloading etc.  No need to remove unreferenced objects because there is Automatic Garbage Collection in java.
  • 9.  Object-oriented means we organize our software as a combination of different types of objects that incorporates both data and behaviour.  Object-oriented programming(OOPs) is a methodology that simplify software development and maintenance by providing some rules.  Basic concepts of OOPs are:  Object  Class  Inheritance  Polymorphism  Abstraction  Encapsulation
  • 10.  A platform is the hardware or software environment in which a program runs.  Java code can be run on multiple platforms e.g. Windows, Linux, Sun Solaris, Mac/OS etc.  Java code is compiled by the compiler and converted into bytecode.  This bytecode is a platform independent code because it can be run on multiple platforms  i.e. Write Once and Run Anywhere(WORA).
  • 11.
  • 12.  Java is secured because: No explicit pointer Programs run inside virtual machine sandbox.  Classloader- adds security by separating the package for the classes of the local file system from those that are imported from network sources.  Bytecode Verifier- checks the code fragments for illegal code that can violate access right to objects.  Security Manager- determines what resources a class can access such as reading and writing to the local disk.  These security are provided by java language.  Some security can also be provided by application developer through SSL,JAAS,cryptography etc.
  • 13.
  • 14.  Robust simply means strong.  Java uses strong memory management.  There are lack of pointers that avoids security problem.  There is automatic garbage collection in java.  There is exception handling and type checking mechanism in java.  All these points makes java robust.  compile time error checking and runtime checking.
  • 15.  There is no implementation dependent features e.g. size of primitive types is set.  Java compiler generates an architecture- neutral object file format which makes the compiled code to be executable on many processors, with the presence of Java runtime system.
  • 16. High-performance  Java is faster than traditional interpretation since byte code is "close" to native code still somewhat slower than a compiled language (e.g., C++) Portable  We may carry the java bytecode to any platform.
  • 17.  We can create distributed applications in java.  RMI and EJB are used for creating distributed applications.  We may access files by calling the methods from any machine on the internet.
  • 18.  A thread is like a separate program, executing concurrently.  We can write Java programs that deal with many tasks at once by defining multiple threads.  The main advantage of multi-threading is that it shares the same memory.  Threads are important for multi-media, Web applications etc.
  • 19. 2. The Java Programming Environment 3. Fundamental Programming Structures in Java
  • 20.  To create a simple java program, you need to create a class that contains main method.
  • 21. For executing any java program, you need to:  install the JDK.  set path of the jdk/bin directory.  create the java program  compile and run the java program
  • 22.  The path is required to be set for using tools such as javac, java etc.  If you are saving the java source file inside the jdk/bin directory, path is not required to be set because all the tools will be available in the current directory.  But If you are having your java file outside the jdk/bin folder, it is necessary to set path of JDK. There are 2 ways to set java path:  temporary  permanent
  • 23. To set the temporary path of JDK, you need to follow following steps:  Open command prompt  copy the path of jdk/bin directory  write in command prompt: set path=copied_path  For Example: setpath=C:Program FilesJavajdk1.7.0_67bin
  • 24.
  • 25.  For setting the permanent path of JDK, you need to follow these steps:  Go to MyComputer properties -> advanced tab -> environment variables -> new tab of user variable -> write path in variable name - > write path of bin folder in variable value -> ok -> ok -> ok
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.  Now your permanent path is set. You can now execute any program of java from any drive.
  • 36. class Simple{ public static void main(String args[]){ System.out.println("Hello Java"); } } _____________________________________ save this file as Simple.java ______________________________________ To compile:javac Simple.java To execute:java Simple ______________________________________ Output:Hello Java
  • 37.  Let's see what is the meaning of class, public, static, void, main, String[], System.out.println().  class keyword is used to declare a class in java.  public keyword is an access modifier which represents visibility, it means it is visible to all.
  • 38.  static is a keyword, if we declare any method as static, it is known as static method. The core advantage of static method is that there is no need to create object to invoke the static method. The main method is executed by the JVM, so it doesn't require to create object to invoke the main method. So it saves memory.  void is the return type of the method, it means it doesn't return any value.  main represents startup of the program.  String[] args is used for command line argument. We will learn it later.  System.out.println() is used print statement. We will learn about the internal working of System.out.println statement later.
  • 39.  To write the simple program, open notepad by start menu -> All Programs -> Accessories -> notepad and write simple program as displayed below:
  • 40.
  • 41.  As displayed in the above diagram, write the simple program of java in notepad and saved it as Simple.java. To compile and run this program, you need to open command prompt by start menu -> All Programs -> Accessories -> command prompt.
  • 42.
  • 43.
  • 44.  To compile and run the above program, go to your current directory first; my current directory is c:new .  Write here:  To compile:javac Simple.java  To execute:java Simple
  • 45.  There are many ways to write a java program. The modifications that can be done in a java program are given below:
  • 46. 1) By changing sequence of the modifiers, method prototype is not changed.  Let's see the simple code of main method.  static public void main(String args[])
  • 47. 2) subscript notation in java array can be used after type, before variable or after variable.  Let's see the different codes to write the main method.  public static void main(String[] args)  public static void main(String []args)  public static void main(String args[])
  • 48. 3) You can provide var-args support to main method by passing 3 ellipses (dots)  Let's see the simple code of using var-args in main method. We will learn about var-args later in Java New Features chapter.  public static void main(String... args)
  • 49. 4) Having semicolon at the end of class in java is optional. Let's see the simple code. class A{ static public void main(String... args){ System.out.println("hello java4"); } };
  • 50.  public static void main(String[] args)  public static void main(String []args)  public static void main(String args[])  public static void main(String... args)  static public void main(String[] args)  public static final void main(String[] args)  final public static void main(String[] args)  final strictfp public static void main(String[] ar gs)
  • 51.  public void main(String[] args)  static void main(String[] args)  public void static main(String[] args)  abstract public static void main(String[] args)
  • 52. Resolving an error "javac is not recognized as an internal or external command" ?  If there occurs a problem like displayed in the below figure, you need to set path.  Since DOS doesn't know javac or java, we need to set path.  Path is not required in such a case if you save your program inside the jdk/bin folder. But its good approach to set path.
  • 53.
  • 54.
  • 55.
  • 56.  what happens while compiling and running the java program.  What happens at compile time?  At compile time, java file is compiled by Java Compiler (It does not interact with OS) and converts the java code into bytecode.
  • 57.
  • 58.
  • 59.  Classloader: is the subsystem of JVM that is used to load class files.  Bytecode Verifier: checks the code fragments for illegal code that can violate access right to objects.  Interpreter: read bytecode stream then execute the instructions.
  • 60. Q. Can you save a java source file by other name than the class name? ANS: Yes, if the class is not public. It is explained in the figure given below:
  • 61.  To compile:javac Hard.java  To execute:java Simple
  • 62. Q) Can you have multiple classes in a java source file?  Yes, like the figure given below illustrates:
  • 63.
  • 64.  JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in which java bytecode can be executed.  JVMs are available for many hardware and software platforms.  JVM, JRE and JDK are platform dependent because configuration of each OS differs.  But, Java is platform independent.  The JVM performs following main tasks:  Loads code  Verifies code  Executes code  Provides runtime environment
  • 65.  JRE is an acronym for Java Runtime Environment.  It is used to provide runtime environment.  It is the implementation of JVM.  It physically exists.  It contains set of libraries + other files that JVM uses at runtime.  Implementation of JVMs are also actively released by other companies besides Sun Micro Systems.
  • 66.
  • 67.  JDK is an acronym for Java Development Kit.  It physically exists.  It contains JRE + development tools.
  • 68.  java: Serves as a java interpreter used to run java applets and applications by reading and interpreting bytecode.  javac: servers as java compiler used to translate java source code to bytecode files.  javadoc: Creates HTML documentation for java source files.  javap: java is disassembler used to convert bytecode files into java program description.  jdb: java debugger used to find errors in java program.
  • 69.  appletviewer: facilities to run java applet.  jar: contains package related libraries into a single executable java archive file(JAR).
  • 70. The JVM performs following operation:  Loads code  Verifies code  Executes code  Provides runtime environment JVM provides definitions for the:  Memory area  Class file format  Register set  Garbage-collected heap  Fatal error reporting etc.
  • 71.  It is a collection of classes, interfaces and methods which are provide in the form of java package.  It is a large already created classes , interfaces and methods which provides many useful capabilities like, GUI, Date, time ,calender.
  • 72.  java.lang: provides classes that are fundamental to the design for java programming language.  java.util: provides legacy collection classes, event model, collection framework, date and time capabilites, etc,  java.io: provides classes for system input and output through data streams, serialization and the file system.  java.awt: classes to create user interface and painting graphics images.  java.applet: provids classes necessary to create applet and used to communicate with its applet contex.  java.net:Provides classes that are used to implement networking in java programs.
  • 73. 1.The Java Platform, Standard Edition(Java SE):  Helps to develop desktop and console based applications.  Most commonly used.  Contains java API, run time environment. 2. The Java Platform, Enterprise Edition(Java EE): Helps to build server-side applications. 3. The Java Platform, Micro Edition(Java ME):Helps to build java application for micro devices, which includes hand-held devices like, mobile phone, PDA’s etc.
  • 74.  Variable is a name of memory location.  Variables are nothing but reserved memory locations to store values.  This means that when you create a variable you reserve some space in memory.  Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory.  Therefore, by assigning different data types to variables, you can store integers, decimals, or characters in these variables. 24-12-2014, 4:15 to 5:15
  • 75. Variable  Variable is name of reserved area allocated in memory.  int data=10;//Here data is variable
  • 76. There are three types of variables:  Local  instance  static. There are two data types available in Java:  Primitive Data Types  Reference/Object Data Types(and non- primitive)
  • 77. There are three types of variables in java  Local variable  instance variable  static variable
  • 78.  Local variables are declared in methods, constructors, or blocks.  Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor or block.  Access modifiers cannot be used for local variables.  Local variables are visible only within the declared method, constructor or block.  There is no default value for local variables so local variables should be declared and an initial value should be assigned before the first use.
  • 79.  Instance variables are declared in a class, but outside a method, constructor or any block.  Instance variables are created when an object is created with the use of the keyword 'new' and destroyed when the object is destroyed.  Access modifiers can be given for instance variables  The instance variables are visible for all methods, constructors and block in the class. Normally, it is recommended to make these variables private (access level).  Instance variables have default values.
  • 80.  “Class variables” are also known as static variables  Are declared with the static keyword in a class, but outside a method, constructor or a block.  There would only be one copy of each class variable per class, regardless of how many objects are created from it.  Static variables are stored in static memory.  Static variables are created when the program starts and destroyed when the program stops.
  • 81. class A{ int data=50;//instance variable static int m=100;//static variable void method(){ int n=90;//local variable } }//end of class
  • 82.
  • 83. Every variable in JAVA has a data type. Data types specify the size and type of values that can be stored.
  • 84.  Primitive types are also known as simple data types•  A primitive type is predefined by the language•
  • 85.  Non-primitive types are also known as reference types• Non-primitive types are :  Classes  Interfaces  Arrays
  • 86.  Java defines four integer types: byte, short, int and long.  All these are signed, positive and negative values•  Java does not support unsigned types•  byte is 8 bit width , short is 16 bit width int is 32 bit width and long is 64 bit width.
  • 87.  The smallest integer type is byte •  Range from -128 to +127•  Byte variables are declared by use of keyword ‘byte ‘  Variables of type byte are especially useful when you’re working with a stream of data from a network or file.  eg. byte x, y;
  • 88.  Short is a signed 16-bit type.  It has a range from –32,768 to 32,767.  It is probably the least-used Java type.  Here are some examples of short variable declarations: short s; short t;
  • 89.  The most commonly used integer type is int.  It is a signed 32-bit type  Range from –2,147,483,648 to 2,147,483,647.  In addition to other uses, variables of type int are commonly employed to control loops and to index arrays.  e.g: int x;
  • 90.  long is a signed 64 bit type•  Useful where an int type is not large enough to hold the desired value•  The range of large is quite large•  This makes it useful when large, whole numbers are needed•  Keyword used is ‘long’  eg. : long seconds;
  • 91. // Compute distance light travels using long variables. class Light { public static void main(String args[]) { int lightspeed; long days; long seconds; long distance; // approximate speed of light in miles per second lightspeed = 186000; days = 1000; // specify number of days here seconds = days * 24 * 60 * 60; // convert to seconds distance = lightspeed * seconds; // compute distance System.out.print("In " + days); System.out.print(" days light will travel about "); System.out.println(distance + " miles."); } } output: In 1000 days light will travel about 16070400000000 miles.
  • 92.  floating point numbers are also known as real numbers•  Are used when fractional components are required•  float and double are two kinds of floating point types•  Keywords used are ‘float’ and ‘double’
  • 93.  float specify a single precision value that uses 32 bits of storage•  float type is useful when you require fractional component to save.  eg. float area; float hightemp, lowtemp;
  • 94.  Double precision, as denoted by the double keyword, uses 64 bits to store a value. Double  Double precision is actually faster than single precision on some modern processors that have been  optimized for high-speed mathematical calculations.
  • 95. // Compute the area of a circle. class Area { public static void main(String args[]) { double pi, r, a; r = 10.8; // radius of circle pi = 3.1416; // pi, approximately a = pi * r * r; // compute area System.out.println("Area of circle is " + a); } } Output:Area of circle is 366.436224
  • 96.  In Java the data type used to store character is char•  char in Java is different from char in C and C++•  Java used Unicode to represent characters•  Java character is 16 bit type.  The range of the characters is 0 to 65,536
  • 97. // Demonstrate char data type. class CharDemo { public static void main(String args[]) { char ch1, ch2; ch1 = 88; // code for X ch2 = 'Y'; System.out.print("ch1 and ch2: "); System.out.println(ch1 + " " + ch2); } } Output:ch1 and ch2: X Y
  • 98. // char variables behave like integers. class CharDemo2 { public static void main(String args[]) { char ch1; ch1 = 'X'; System.out.println("ch1 contains " + ch1); ch1++; // increment ch1 System.out.println("ch1 is now " + ch1); } } Output: ch1 contains X ch1 is now Y
  • 99.  boolean data type is used to represent logical values that can be either true or false•  All relational, conditional and logical operators return boolean values•  It used only one bit of storage•  Keyword used is ‘boolean’•  eg;. boolean flag;
  • 100.  byte----- 0  short----- 0  int---- 0  long---- 0L  float-------0.0f  double------0.0d  char--------’u000’  boolean ----- false
  • 101.  Variables are container or placeholder, since the values stored in them can be changed during the execution.
  • 102.  You must declare a variable before using it in a program.  Syntax: dataType variable;//declaring variable  dataType specifies valid dataType like int, float etc  Variables can be any name.  Can declare more than one variable: dataType variable1,variable2,...variableN;
  • 103.  After declaration, can assign value to the variable.  Assigning value to the variable ,know as a initializing variables.  dataType variable=val; OR  dataType variable; ----- ----- variable=val;
  • 104.  int a, b, c; // declares three ints, a, b, and c.  int d = 3, e, f = 5; // declares three more ints, initializing d and f.  byte z = 22; // initializes z.  double pi = 3.14159; // declares an approximation of pi.  char x = 'x'; // the variable x has the value 'x'
  • 105.  Type casting is the process of converting an entity of one data type into another data type.  If the two types are compatible, then Java will perform the conversion automatically.  For example, it is always possible to assign an int value to a long variable.  However, not all types are compatible, and thus, not all type conversions are implicitly allowed.  For instance, there is no automatic conversion defined from double to byte.  It is still possible to obtain a conversion between incompatible types  26-12-2014, 5 :15 -6:15
  • 106.  Following are the two ways of conversions included in typecasting: 1. Automatic Type Casting 2. Casting Incompatible Data Types.
  • 107.  When one type of data is assigned to another type of variable, an automatic type conversion will take place.  Two data type being used must be compatible with each other.  The destination type is larger than the source type.  Numeric data types, such as int and float are compatible to each other.  Where as int, float is not compatible with boolean and char data types.  “widening conversion” takes place here.
  • 108. class AutoCastDemo { public static void main(String[] args) { int i= 150; long l; l=i; System.out.println("The value of Long variable is::"+ l); } } Output: The value of Long variable is::150
  • 109.  When you assign large data value to a variable of data type that cant not hold the assigned value, then need explicit type casting: Target_Variable=(target_data_type) Source_Variable;  Target_Variable=in which data is to be assigned.  target_data_type= is the data type of the Target_Variable.  Source_Variable=variable whose value is being assigned to Target_Variable.
  • 110. public class ExplicitCastDemo { public static void main(String[] args) { int i; long l=200; i=(int)l; System.out.println("The value of INT variable is::"+ i); } } output:The value of INT variable is::200
  • 111. Rules:  All byte, short, and char values are promoted to int.  Then, if one operand is a long, the whole expression is promoted to long.  If one operand is a float, the entire expression is promoted to float.  If any of the operands is double, the result is double.
  • 112. class Promote { public static void main(String args[]) { byte b = 42; char c = 'a'; short s = 1024; int i = 50000; float f = 5.67f; double d = .1234; double result = (f * b) + (i / c) - (d * s); System.out.println((f * b) + " + " + (i / c) + " - " + (d * s)); System.out.println("result = " + result); } }
  • 113.  Type promotions that occur in this line from the program: double result = (f * b) + (i / c) - (d * s); =(float+int)-double =float-double =double  f * b, b is promoted to a float and the result of the subexpression is float.  the subexpression i/c, c is promoted to int and the result is of type int.  In d*s, the value of s is promoted to double, and the type of the subexpression is double.  Finally, these three intermediate values float, int and double are considered.
  • 114.  The outcome of float plus an int is a float.  Then the resultant float minus the last double is promoted to double,  which is the type for the final result of the expression.
  • 115.  After declaring variable as a final, you can not assign any other value to that variable.  In C and C++ constants defined using #define statements.  In java constants are used by keyword final.  final variable should be declare at the beginning of the class as a class member and not within a method.  final double pi=3.14;
  • 116.  Literal in Java refer to fixed values that do not change during the execution of the program•  Java supports several types of constants • 1. Integer Literal • 2. Real Literal (Floating -point)• 3. Character Literal • 4. Boolean Literal. 5. String Literal •
  • 117.  An integer literal refers to sequence of digits• Integers are of three types• They are • 1. Decimal Integer 2. Octal Integer 3. Hexadecimal Integer
  • 118. Decimal Integer:  Decimal Integers consists of a set of digits from 0 to 9,preceeded by an optional minus(- ) sign  Used as base 10.  eg. : +999,-999•  Embedded spaces ,commas and non-digit characters are not permitted in between digits  eg. 99 999, 99,999 , $999 are illegal numbers.
  • 119. //Program for Decimal literals public class DecimalLit { public static void main(String[] args) { int sixteen=16; System.out.println("Decimal Sixteen="+sixteen); } } //Output: Decimal Sixteen=16
  • 120. Octal Integer:  Base of octal number system is 8.  Digits from 0-7 are same as decimal number system.  Number 8 of decimal number system is represented by 10, 9 by 11 and so on.  An octal integer consists of any combination of digits from 0 to 7 with a leading zero(0) eg. 045,063,026
  • 121. //Program for octal literals public class OctalLit { public static void main(String[] args) { int five=05; //Value of five is equal to decimal 5 int eight=010; //Value of eight is equal to decimal 8 int ten=012; //Value of ten is equal to decimal 10 System.out.println("Octal value of 012 is equivalent to::"+ten+"in decimal"); } } //Output: Octal value of 012 is equivalent to::10 in decimal
  • 122. Hexa Decimal Integer:  A sequence of digits preceded by 0x or 0X is considered as hexa decimal integers•  They may also include alphabets from A to F or a to f•  Letters from a to f represents the numbers from 10 to 15  eg. 0xd,0XF etc.,  Base 16.
  • 123. //Program for Hexadecimal literal public class HexadecimalLit { public static void main(String[] args) { int a=0x5; //value of a is equvalent to decimal 5 int b=0xF; //value of b is equvalent to decimal 15 int c= 0Xd; //value of c is equvalent to decimal 13 System.out.println("Decimal five::"+a); System.out.println("Decimal fifteen::"+b); System.out.println("Decimal thirteen::"+c); } } /*Output:: Decimal five::5 Decimal fifteen::15 Decimal thirteen::13 */
  • 124. Real Literals:  Numbers containing fractional parts are called real literals/ Floating-point literals.  eg. 9.999,0.999 etc.,•  Floating-point numbers are like real numbers in mathematics,  for example, 4.13179, -0.000001.  Java has two kinds of floating-point numbers: float and double.  float temp=7.86f// correct  float hight=6.45;//generate an error;  double distance=67.895432d;//correct  double distance1=876.9876;//correct
  • 125.  The default type when you write a floating- point literal is double, but you can designate it explicitly by appending the D (or d) suffix.  However, the suffix F (or f) is appended to designate the data type of a floating-point literal as float.  We can also specify a floating-point literal in scientific notation using Exponent (short E or e).  Examples include 6.022E23, and 2e+100.
  • 126. class FloatingPointLit{ public static void main(String args[]){ float hight=6.45f; System.out.println("Hight::"+hight); } } //Output: Hight::6.45
  • 127.  char data type is a single 16-bit Unicode character.  single printable character literal denotes in a pair of single quote characters such as 'a', '#', and '3'.  You must know about the ASCII character set.  The ASCII character set includes 128 characters including letters, numerals, punctuation etc..  char letter=‘A’;  char value=‘Y’;  char newline=‘n’;  char character j=‘u004A’;
  • 128. String Literals:  A String Literal is a sequence of characters enclosed between double quote marks “ “  The characters may be alphabets, digits, special characters and blank spaces  eg. “SGGSIE & T”  String is considered as a class insteated of primitive data type.  As Sting literals are converted by the compiler into string objects,
  • 129.  The values true and false are treated as literals in Java programming.  When we assign a value to a boolean variable, we can only use these two values.  Unlike C, we can't presume that the value of 1 is equivalent to true and 0 is equivalent to false in Java.  We have to use the values true and false to represent a Boolean value. Example boolean chosen = true; //correct Boolean temp=1;// Generate an error  Remember that the literal true is not represented by the quotation marks around it.  The Java compiler will take it as a string of characters, if its in quotation marks.
  • 130.
  • 131.  An operator is a symbol that allows a programmer to perform certain arithmetic and logical operations on data and variables.  There are different types of operators available in Java: 1. Arithmetic 2. Increment and Decrement 3. Relational 4. Logical 5. Bitwise 6. Conditional 7. Special(instanceOf and dot)
  • 132.  Arithmetic operators are used in mathematical expressions.
  • 133. //Performing Addition and Subtraction on double data type variables public class IntAddSub { public static void main(String[] args) { double a=50.5; double b=30.4; System.out.println("First number is:"+a); System.out.println("Second number is:"+b); double c=a+b; System.out.println("Addition of two number is:"+c); c=a-b; System.out.println("Sustraction of two number is:"+c); } } /*OUTPUT:First number is:50.5 Second number is:30.4 Addition of two number is:80.9 Sustraction of two number is:20.1*/
  • 134. The Modulus Operator  The modulus operator,%, returns the remainder of a division operation.  It can be applied to floating-point types as well as integer types.
  • 135. // Demonstrate the % operator. class Modulus { public static void main(String args[]) { int x = 42; double y = 42.25; System.out.println("x mod 10 = " + x % 10); System.out.println("y mod 10 = " + y % 10); } } output: x mod 10 = 2 y mod 10 = 2.25
  • 136. Arithmetic Compound Assignment Operators:  Java provides special operators that can be used to combine an arithmetic operation with an assignment.  Common Programming: a = a + 4;  In Java, you can rewrite this statement as shown here: a += 4;  This version uses the+=compound assignment operator.  Both statements perform the same action: they increase the value of a by 4.
  • 137. // Demonstrate several assignment operators. class OpEquals { public static void main(String args[]) { int a = 1; int b = 2; int c = 3; a += 5; //a=a+5; b *= 4; c += a * b; c %= 6; System.out.println("a = " + a); System.out.println("b = " + b); System.out.println("c = " + c); } } The output of this program is shown here: a = 6 b = 8 c = 3
  • 138.  ++ and the - - are Java's increment and decrement operators.  The increment operator increases its operand by one.  x++; is equivalent to x = x + 1;  The decrement operator decreases its operand by one.  y--; is equivalent to y = y – 1;  They can appear both in • postfix form, where they follow the operand, and • prefix form, where they precede the operand.
  • 139.  Prefix: The value of the operand is incremented and decremented before assigning it to the another variable.  Example: x = 19; y = ++x; Output: y = 20 and x = 20  Postfix: The value of the operand is incremented or decremented after assigning it to another variable.  Example: x = 19; y = x++; Output: y = 19 and x = 20
  • 140.
  • 141.  A relational operator compares two values and determines the relationship between them.  For example, != returns true if its two operands are unequal.  Relational operators are used to test whether two values are equal, whether one value is greater than another, and so forth.
  • 142.
  • 143.
  • 144. public LessThanExample { publi cstatic void main(String args[]) { int a = 5; int b = 10; if(a < b) { System.out.println("a is less than b"); } } }
  • 145.  The Boolean logical operators shown here operate only on boolean operands.  All of the binary logical operators combine two boolean values to form resultant boolean value.
  • 146.
  • 147.
  • 148.
  • 149. public class Test { public static void main(String args[]) { int a = 10; int b = 20; System.out.println("a == b = " + (a == b) ); System.out.println("a != b = " + (a != b) ); System.out.println("a > b = " + (a > b) ); System.out.println("a < b = " + (a < b) ); System.out.println("b >= a = " + (b >= a) ); System.out.println("b <= a = " + (b <= a) ); } }
  • 150.  This would produce the following result: a == b = false a != b = true a > b = false a < b = true b >= a = true b <= a = false
  • 151.  Java defines several bitwise operators that can be applied to the integer types, long, int, short, char and byte.  These operators act upon the individual bits(0 and 1) of their operands.
  • 152.
  • 153. Bitwise Logical Operators :  The bitwise logical operators are • 1. ~ (NOT) 2. & (AND) 3. | (OR) 4. ^ (XOR)
  • 154. The Left Shift  The left shift operator,<<, shifts all of the bits in a value to the left a specified number of times. value << num Example: 01000001 65 << 2 00000100
  • 155. The Right Shift  The right shift operator, >>, shifts all of the bits in a value to the right a specified number of times. value >> num Example: 00100011 35 >> 2 00001000  When we are shifting right, the top (leftmost) bits exposed by the right shift are filled in with the previous contents of the top bit.  This is called sign extension and serves to preserve the sign of negative numbers when you shift them right.
  • 156. The Unsigned Right Shift •  In these cases, to shift a zero into the high- order bit no matter what its initial value was. This is known as an unsigned shift.  To accomplish this, we will use Java’s unsigned, shift-right operator, >>>, which always shifts zeros into the high-order bit.  Example: 11111111 11111111 11111111 11111111 –1 in binary as an int >>>24 00000000 00000000 00000000 11111111 255 in binary as an int
  • 157.  combines the assignment with the bitwise operation.  Similar to the algebraic operators  For example, the following two statements, which shift the value in a right by four bits, are equivalent: a = a >> 4; a >>= 4;  Likewise, a = a | b; a |= b;
  • 158.  Java includes a special ternary (three- way)operator, ?, that can replace certain types of if-then-else statements.  The ? has this general form: expression1 ? expression2 : expression3  Here,expression1 can be any expression that evaluates to a boolean value.  If expression1 is true , then expression2 is evaluated; otherwise, expression3 is evaluated.  The result of the? operation is that of the expression evaluated.  Both expression2 and expression3 are required to return the same type, which can’t be void.
  • 159.  Example: TestTernary.java  ratio = denom == 0 ? 0 : num / denom;  When Java evaluates this assignment expression, it first looks at the expression to the left of the question mark.  If denom equals zero, then the expression between the question mark and the colon is evaluated and used as the value of the entire ? expression.  If denom does not equal zero, then the expression after the colon is evaluated and used for the value of the entire ? expression. •The result produced by the? operator is then assigned to ratio.
  • 160. public class Test { public static void main(String args[]){ int a , b; a = 10; b = (a == 1) ? 20: 30; System.out.println( "Value of b is : " + b ); b = (a == 10) ? 20: 30; System.out.println( "Value of b is : " + b ); } } This would produce the following result: Value of b is : 30 Value of b is : 20
  • 161.  This operator is used only for object reference variables.  The operator checks whether the object is of a particular type(class type or interface type). instanceof operator is written as: ( Object reference variable ) instanceof (class/interface type)  If the object referred by the variable on the left side of the operator passes the IS-A check for the class/interface type on the right side, then the result will be true.
  • 162. public class Test { public static void main(String args[]){ String name = "James"; // following will return true since name is type of String boolean result = name instanceof String; System.out.println( result ); } } This would produce the following result: true
  • 163. class Vehicle {} public class Car extends Vehicle { public static void main(String args[]){ Vehicle a = new Car(); boolean result = a instanceof Car; System.out.println( result ); } } This would produce the following result: true
  • 165.  Java provides a data structure, the array.  which stores a fixed-size sequential collection of elements of the same type.  Array in java is index based, first element of the array is stored at 0 index & last at n-1th index.
  • 166. Advantage of Java Array  Code Optimization: It makes the code optimized, we can retrieve or sort the data easily.  Random access: We can get any data located at any index position. Disadvantage of Java Array  Size Limit: We can store only fixed size of elements in the array.  It doesn't grow its size at runtime.  To solve this problem, collection framework is used in java.
  • 167. There are two types of array. 1. Single Dimensional Array 1. Multidimensional Array
  • 168. data_type var_name[ ];  data_type=data type of the array.  var_name= is the name of the array. Ex: int roll_no [ ]; int [ ] tele_no;
  • 169.  You can create an array by using the new operator with the following syntax: var_name=new data_type [size];  var_name= name of the array declared.  New is the keyword, which is used to allocate memory fo the var_name array.  data_type= Data type of the element stored in the array.  size=Total number of elements that will be stored in array. roll_no=new int[10]; Total number of element stored=10 Memory allocated=40 bytes(10*4)
  • 170.  Array declaration and creation in a single step: int roll_no [ ]= new int[10]; Initializing array: roll_no [0]=121; roll_no [1]=122; roll_no [2]=123; roll_no [3]=124; roll_no [4]=125; roll_no [5]=126; ........ roll_no [9]=130;
  • 171.  Can initialize at the time of declaration, then there is no need:  To use new keyword to assign memory.  No need to specify size of an array. int roll_no [ ]={121,122,123,124,125,126,127,128,129,130};
  • 172. public class ArrayEx1 { public static void main(String[] args) { int x; int even[]; even= new int[5]; even [0]=20; even [1]=12; even [2]=3; even [3]=124; even [4]=10; for(x=0;x<even.length;x++){ if(even[x]%2==0){ } System.out.println(even[x]+"is an even number"); } } }
  • 173.  op: 20is an even number 12is an even number 124is an even number 10is an even number
  • 174. class TestArrayCopyDemo { public static void main(String[] args) { char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e‘,‘i', 'n', 'a', 't', 'e', 'd' }; char[] copyTo = new char[7]; System.arraycopy(copyFrom, 2, copyTo, 0, 7); System.out.println(new String(copyTo)); } } op: caffein
  • 175. class Testarray2{ static void min(int arr[]){ int min=arr[0]; for(int i=1;i<arr.length;i++) if(min>arr[i]) min=arr[i]; System.out.println(min); } public static void main(String args[]){ int a[]={33,3,4,5}; min(a);//passing array to method }} op: 3
  • 176.  Data is stored in row and column based index (also known as matrix form).  dataType arrayRefVar[][];  dataType[][] arrayRefVar; (or)  dataType [][]arrayRefVar; (or) instantiate Multidimensional Array int[][] arr=new int[3][3];//3 row and 3 column
  • 177.  arr[0][0]=1;  arr[0][1]=2;  arr[0][2]=3;  arr[1][0]=4;  arr[1][1]=5;  arr[1][2]=6;  arr[2][0]=7;  arr[2][1]=8;  arr[2][2]=9;
  • 178.
  • 179.  int arr[] []=new int [4][3];  arr.length=4  arr[i].lengt= 3 _______________________________________ for(i=0;i<arr.length;i++) for(j=0;j<arr[i].lenght;j++) arr[i][j]=Integer.parseInt(obj.readLine());
  • 180. class Testarray3{ public static void main(String args[]){ //declaring and initializing 2D array int arr[][]={{1,2,3},{2,4,5},{4,4,5}}; //printing 2D array for(int i=0;i<3;i++){ for(int j=0;j<3;j++){ System.out.print(arr[i][j]+" "); } System.out.println(); } }} 1 2 3 2 4 5 4 4 5
  • 181. int arr[i][j][k]=new int[2][4][5]; arr.length= 2(No. Of 2-D array) arr[i].length= 4 arr[i][j].length=5  __________________________________ for(i=0;i<arr.length;i++) for(j=0;j<arr[i].length;j++) for(k=0;k<arr[i][j].length;k++) arr[i][j][k]=obj.nextInt();
  • 182.
  • 183.  More than one statement in the initialization and iteration portions of the for loop can be used.  Example 1: class var2 { public static void main(String arr[]) { int a, b; b = 5; for(a=0; a<b; a++) { System.out.println("a = " + a); System.out.println("b = " + b); b--; } } }
  • 184.  o/p: a = 0 b = 5 a = 1 b = 4 a = 2 b = 3
  • 185.  Example 2: class var2 { public static void main(String arr[]) { int x, y; for(x=0, y=5; x<=y; x++, y--) { System.out.println("x= " + x); System.out.println("y="+y);} }}
  • 187.  Beginning with JDK 5, a second form of for was defined that implements a “for-each” style loop.  For-each is also referred to as the enhanced for loop.  Specifically designed for collections.  For-each loop repeatedly executes a group of statements for each element of the collection.  Executes as may times as the number of elements in collection.  Array is a type of a collection.
  • 189. class var2 public static void main(String arg[]) { int arr[]={1,3,5,7,11,13,15,17,19}; System.out.println("First 10 odd numbers are:"); for(int i:arr){ System.out.println(i); } } }
  • 190.  There are various ways to read input from the keyboard, the java.util.Scanner class is one of them.  Scanner class is one of the class of Java which provides the methods to get inputs.  Scanner class is present in java.util package so we import this package in our program.  We first create an object of Scanner class and then we use the methods of Scanner class.
  • 191.  Scanner a = new Scanner(System.in); Following are methods of Scanner class:  next( ) :to input a string  nextByte() :to input a byte value  nextInt( ) :to input an integer  nextFloat( ) :to input a float  nextLong( ) :for Long Values  nextDouble() :for double values
  • 192. import java.util.*; public class InputTest { public static void main(String[] args) { Scanner in = new Scanner(System.in); // get first input System.out.print("What is your name? :"); String name = in.nextLine(); // get second input System.out.print("How old are you? :"); int age = in.nextInt(); // display output on console System.out.println("Hello, " + name + ". Next year, you'll be " + (age + 1)); } }
  • 193.  // System.out.println("We will not use 'Hello, World!'"); // is this too cute?  /*....*/ you can use the /*and */comment delimiters that let you block off a longer comment.  /****........*/ used to generate documentation automatically. This comment uses a /**to start and a */to end.
  • 194.
  • 195.  Java naming convention is a rule to follow as you decide what to name your identifiers such as class, package, variable, constant, method etc.  But, it is not forced to follow. So, it is known as convention not rule.  By using standard Java naming conventions, you make your code easier to read for yourself and for other programmers.  Readability of Java program is very important. It indicates that less time is spent to figure out what the code does.