You are on page 1of 35

Java Programming

Java is a popular high-level object


oriented programming language.

It was designed by James Gosling in


1991 at Sun Microsystems. The first
version of Java was released in 1996.

It derives its syntax from C and C++


programming languages.
Prepared By – Asmita Ranade
Features of Java
• Simple – It has small number of language
constructs which makes it simpler.
• Object Oriented – It supports classes and
objects and OOP features.
• Platform Independent – Java program can run
on various platforms like Windows, Mac, Unix,
Linux etc.
• Portable & Architecture Neutral – Any
machine which supports Java std. can run the
Java programs. Prepared By – Asmita Ranade
Features of Java
• Robust – It is a strongly typed language which allows
extensive compile time error checking.
• Dynamic – It supports dynamic loading of classes. Class
loader is responsible for loading the class dynamically into
JVM.
• Interpreted – It is an interpreted language.
• Multithreaded – It supports multiple threads of execution.
• Distributed – It supports various levels of network
connectivity. TCP/IP support in Java allows us to access
remote objects on the Internet.
Prepared By – Asmita Ranade
Working of C++ and Java
• C/C++ – C/C++ programming
languages are platform dependent.
So we require a different compiler
for different platforms.
• Java – Java is platform
independent and supports
portability. Java compiler produces
a bytecode which can run on any
platform.
Prepared By – Asmita Ranade
Java Environment Architecture
Java uses both approaches of compilation
and interpretation.
After compiling ‘.java’ source file, the
‘javac’ compiler generates ‘.class’ file which
is called as the Bytecode. Bytecode is
independent of the platform or operating
system.
During program execution, JVM interprets
this bytecode to generate the machine code
Prepared By – Asmita Ranade
which is executed to produce the output.
Java Environment Architecture (contd.)

Class Loader – It is a part of the JRE. It


is responsible for dynamically loading
Java classes into JVM.

Byte Code verifier – It is a part of JRE.


Before loading the class file into JVM,
Bytecode verifier inspects the class file
for any errors and instructions which
cannot be executed.
Prepared By – Asmita Ranade
Java Environment Architecture (contd.)
Java Virtual Machine (JVM) – It is used during the program execution
phase. It executes the bytecode i.e. class file generated by the compiler.

Prepared By – Asmita Ranade


Java Environment Architecture (contd.)

Just-In-Time (JIT) Compiler – It is a very


important component of JRE.
It compiles the byte code at runtime to the
native machine code.
Platform independent bytecode is first
interpreted by JVM and then converted to
native machine code by JIT which is then
executed to generate the output.
Prepared By – Asmita Ranade
Java Development Toolkit (JDK)
Java Development Kit (JDK) is a
software development environment
which includes JRE, Java compiler,
Java debugger, JavaDoc etc.
To create, compile and execute Java
programs and applications we require
JDK to be installed on the computer.
Latest version – JDK 19 released in
Sept 2022.
Prepared By – Asmita Ranade
Executing Java Programs
For compiling and executing Java programs we must have JDK installed on
our computer.
JDK is freely available from Oracle.
JDK provides with 2 primary programs –
• javac – Java Compiler
• java – Standard Java Interpreter also known as Application Launcher
JDK runs in the command prompt environment and uses command line tools.
It is not an integrated development environment (IDE).
There are several IDEs available for Java like NetBeans and Eclipse.
Prepared By – Asmita Ranade
Java Class and Objects
Class – It is the basic building block of an object oriented language.
It binds all the data members and functions together.
It is a template from which objects are created. Syntax for declaring a class –
keyword class classname
A class contains the following –
{
• Data members variable declarations
• Methods main function ( )
{
• Constructor Program Logic
• Nested class }
}
• Interface
Prepared By – Asmita Ranade
First Example Program
/* First Java Program example.java */
class example Remember -

{ public static void main(String[] args) Java is case


sensitive.
{ System.out.println(“Java Programming”);
}
}
Here, ‘example’ is the name of the class. The above code is saved in file
‘example.java’. The Java compiler requires that a source file use the .java
filename extension. Prepared By – Asmita Ranade
Compiling Java Program
/* First Java Program - example.java */
class example
{ public static void main(String[] args)
{ System.out.println(“Java Programming”);
}
}

To compile the example.java program, execute the compiler at the command prompt
– javac example.java
The above statement will create a file called ‘example.class’ which contains the
bytecode.
To execute the program use Java interpreter at the command prompt – java example
Prepared By – Asmita Ranade
Understanding Java Program
/* First Java Program - example.java */ Comment
class example class keyword defines
{ a new class
public static void main(String[] args) Program execution
{ begins at main( )
System.out.println(“Java Programming”);
}
}
public keyword is the access modifier. Here, the main( ) is public, so it can be
accessed from outside. static keyword allows main( ) to be called by JVM before any
object of the class is created. Prepared By – Asmita Ranade
Understanding Java Program
/* First Java Program - example.java */ void keyword tells
the compiler that
class example main( ) does not
{ return a value.
public static void main(String[] args) args is the parameter
in the main( ) which
{ receives command
System.out.println(“Java Programming”); line arguments
} Many statements in
} java end with
semicolon
println( ) displays the string passed to it.
System is a predefined class which provides access to the system.
out is the output stream which represents the console. Prepared By – Asmita Ranade
Variables in Java
A variable is a named memory location in which a value can be stored.
Value of a variable can be changed during the execution of the program.
All Java variables must be identified with unique names or identifiers.
Rules for naming variables –
• Name can contain alphabets, digits, underscores and dollar sign.
• Name can begin with a lowercase alphabet, $ or _.
• Names cannot contain whitespace.
• Reserved keywords cannot be used as variable names.
• Names are case sensitive.
Prepared By – Asmita Ranade
Types of Variables in Java
There are 3 types of variables in Java –
• Local Variable – Local variable is a variable which is declared in local scope.
E.g. a variable declared inside a method.
‘Static’ keyword cannot be used for local variables.
• Instance Variable – These are non-static variables which are declared inside a
class but outside the method. The values of these variables are instance specific.
• Static Variable – Static variable is declared with ‘static’ keyword. It cannot be a
local variable. Single copy of a static variable exists and is shared among all the
instances of the class. Memory is allocated only once to the static variable when
the class is loaded. Prepared By – Asmita Ranade
Scope of Variables in Java
Scope refers to the region in the entire program where the variable is
accessible.
• Class Scope – Local variables which are declared inside a class with private
access modifier but outside any method has a class scope. So, these variables are
accessible everywhere in the class but not outside the class.
‘Static’ keyword cannot be used for local variables.
• Method Scope – Variables which are declared inside a method have method
scope. They are not accessible outside the method.
• Loop Scope – Variables which are declared inside a loop have loop scope. They
are not accessible outside the loop. Prepared By – Asmita Ranade
Primitive Data types in Java
Data type Size Description
byte 1 byte Stores whole numbers from -128 to 127
short 2 bytes Stores whole numbers from -32768 to 32767
int 4 bytes Stores whole numbers from -2147483648 to 2147483647
Stores whole numbers from -9223372036854775808 to
long 8 bytes
9223372036854775807
Stores fractional numbers. Sufficient for storing 6 to 7
float 4 bytes
decimal digits.
Stores fractional numbers. Sufficient for storing 15 decimal
double 8 bytes
digits.
boolean 1 bit Stores true or false values
char 2 bytes Stores a single character/letter or ASCII values
Prepared By – Asmita Ranade
Java Operators
For performing operations on variables and values, operators are used.
Java provides with following operators –
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Bitwise operators

Prepared By – Asmita Ranade


Arithmetic operators in Java

Operator Description Example


+ Addition Performs addition of 2 values X+y
- Subtraction Performs subtraction of 2 values X-y
* Multiplication Performs multiplication of 2 values X*y
/ Division Performs division of 2 values x/y
Returns the remainder after division X%y
% Modulus
operation
++ Increment Increases the value of a variable by 1 X++, ++x
-- Decrement Decreases the value of a variable by 1 X--, --x

Prepared By – Asmita Ranade


Assignment operators in Java
Assignment operator = is used to assign value to a variable.
E.g. x=10; Here, value 10 is assigned to variable x.

Following is the list of Compound / Composite Assignment operators -

Operator Example Same as Output


(Assume X = 1)
+= X += 5 X=X+5 X=6
-= X -= 5 X=X-5 X = -4
*= X *= 5 X=X*5 X=5
/= X /= 5 X=X/5 X=0
%= X %= 5 X=X%5 X=1
Prepared By – Asmita Ranade
Comparison operators in Java
Comparison / Relational operators are used to compare 2 values. It is used to create a
condition. Result of comparison is a boolean value True or False.

Operator Example Output


(Assume X = 1)
== Equal to X == 5 False
!= Not equal to X != 5 True
> Greater than X>5 False
< Less than X<5 True
>= Greater than or equal to X >= 5 False
<= Less than or equal to X <= 5 True

Prepared By – Asmita Ranade


Logical operators in Java
Logical operators are used to combine conditions. Result of logical operator is a
boolean value True or False.

Operator Description Example Output


(Assume X = 1
and Y = 10)
& AND Returns true if both conditions are True
X < 5 && Y > 2
&& true
| OR Returns true if one of the True
X > 12 || Y > 2
|| condition is true
! NOT Returns the negation ! ( X ==1) False

&& and || are Short-Circuit Logical operators.


Prepared By – Asmita Ranade
Command Line Arguments
A command line argument is the information which directly follows the
program’s name on the command line when it is executed.
To access the command line arguments inside the program we need to access the
String array passed to the main( ).
class cmdargs
{
public static void main(String args[])
{
System.out.println(“Name is " + args[0]);
}
}

Prepared By – Asmita Ranade


Using Type Wrappers to convert numeric strings

Java’s type wrappers are classes that encapsulate or wrap the primitive data types.
The type wrappers are –

Wrapper Conversion Method


Double Double.parseDouble( ) – converts string to double
Float Float.parseFloat() – converts string to float
Integer Integer.parseInteger( ) – converts string to integer
Long Long.parseLong( ) – converts string to long
Short Short.parseShort( ) – converts string to short
Byte Byte.parseByte( ) – converts string to byte

Prepared By – Asmita Ranade


Decision Making Statements

• Ternary operator
• if statement
• if – else statement
• if – else – if ladder
• nested if statement
• switch case structure

Prepared By – Asmita Ranade


Ternary operator / Conditional operator

?: is called as Ternary / Conditional operator in Java.


Condition is designed using
Syntax – comparison/relational operators.
Condition ? Expression 1 : Expression 2 ;

Here, condition results in boolean value True or False.


Expression 1 and Expression 2 are expressions of any type other than void.
The type of both Expressions must be same or compatible.
If the condition results in True value then Expression 1 is executed.
If the condition results in False value then Expression 2 is executed.
Prepared By – Asmita Ranade
if statement
The if statement determines the flow of the program execution based on whether
some condition is true or false.
If the condition is true then the block of statements gets executed.
If the condition is false, the block is bypassed.

Syntax – Condition is designed using comparison/relational


if (condition ) operators.
Condition results in Boolean value – True or False .
{
//Block
}
Prepared By – Asmita Ranade
if – else statement
Syntax – If the condition is true then Block1 gets
if (condition )
executed otherwise Block 2 gets executed.
{
//Block 1
}
else
{
// Block 2
}
Prepared By – Asmita Ranade
if – else – if ladder statement
Syntax – Here, the conditions are evaluated downwards from
if (condition 1)
{ the top.
//Block 1 When the true condition is found the corresponding
}
else if (condition 2) block gets executed. Rest of the ladder is bypassed.
{ If none of the condition results in true, then the final
// Block 2
} else block is executed.
else
{
//Block 3
}
Prepared By – Asmita Ranade
Nested if statement
Syntax – In Nested if statement, there is a if block inside
if (condition 1)
{ another if block.
//Block 1 Here inner if block (i.e. Block 2) will be executed
if (condition 2)
{ only when the outer condition is true.
// Block 2
}
}

Prepared By – Asmita Ranade


Switch case structure

Syntax – Switch case structure enables a program to select among several


switch ( expression ) alternatives.
{ Here, value of the expression is successively tested against a list of
case value1 : Block1
values. When a match is found, the corresponding block is executed
break;
case value2 : Block2 until a break is encountered.
break; If the expression does not match any given values then the default
case value3 : Block3
block is executed. The default statement is optional.
break;
.. Values mentioned in case statements must be unique. Duplicate case
.. values are not allowed.
..
The type of each value must be compatible with the type of
default : DefaultBlock
} expression.
Prepared By – Asmita Ranade
Taking a character input
To read a character from the keyboard, we can use System.in.read( )
method.
System.in is the input object attached to the keyboard.
read( ) method is used to read a single character from the input stream.
The character read is returned as an integer value which is in the range of
0 to 65535. It returns -1 if no character has been read.
This method also throws IOException if some error occurs during I/P and
O/P operation. It is a part of Java’s exception handling mechanism.
Prepared By – Asmita Ranade
Taking a character input (Example)
class charinput
{ public static void main(String args[]) throws java.io.IOException
{ System.out.print("Enter an alphabet ");
char ch = (char)System.in.read();
System.out.println("Entered alphabet is "+ ch);
}
}

Prepared By – Asmita Ranade

You might also like