Java Programming Basics Overview
Java Programming Basics Overview
III Semester
Course Instructor
Mrs. Revathi K
Assistant Professor,
Dept. of CSE, EPCET
MODULE 1 24CS36A
MODULE - 1
An Overview of Java: Object-oriented programming (Two Paradigms, Abstraction, The Three OOP
Principles), Using Blocks of Code, Lexical Issues (Whitespace, Identifiers, Literals, Comments,
Separators, The Java Keywords).
Data Types, Variables, and Arrays: The Primitive Types (Integers, Floating-Point Types, Characters,
Booleans), Variables, Type Conversion and Casting, Automatic Type Promotion in Expressions,
Arrays, Introducing Type Interference with Local Variables.
Operators: Arithmetic Operators, Relational Operators, Boolean Operators, Logical Operators, The
Assignment Operator, The? Operator, Operator Precedence, Using Parentheses.
Control Statements: Java’s Selection Statements (if, The Traditional Switch), Iteration Statements
(while, do-while, for, The For-Each Version of the Loop, Local Variable Type Inference in a for Loop,
Nested Loops), Jump Statements (Using break, Using continue, return).
Text book: Ch 2, 3, 4, 5
MODULE 1 24CS36A
Bytecode is the compiled format for Java programs. Once a Java program has been converted
to bytecode, it can be transferred across a network and executed, which makes JAVA a
platform Independent Language.
Java Development Kit (JDK):
Java Development Kit contains two parts.
One part contains the utilities like javac, debugger, jar which helps in compiling the
source code (.java files) into byte code (.class files) and debug the programs.
The other part is the JRE, which contains the utilities like java which help in
running/executing the byte code.
Java Run-time Environment helps in running the programs. JRE contains the JVM, the java
classes/packages and the run-time libraries. If we do not want to write programs, but only
execute the programs written by others, then JRE alone will be sufficient.
Java Virtual Machine is important part of the JRE, which actually runs the programs (.class
files), it uses the java class libraries and the run-time libraries to execute those programs. Every
operating system (OS) or platform will have a different JVM.
MODULE 1
OOP-BCS306A
JIT is a module inside the JVM which helps in compiling certain parts of byte code
into the machine code for higher performance. Note that only certain parts of byte
code will be compiled to the machine code, the other parts are usually interpreted
and executed.
Write Once and Run Anywhere (WORA) / CORA (Compile Once and run
anywhere)
Java allows run Java bytecode on any machine irrespective of the machine or the
hardware, using JVM (Java Virtual Machine). The bytecode generated by the compiler
is not platform-specific and hence takes help of JVM to run on a wide range of machines.
So we can call Java programs as a write once and run on any machine residing anywhere.
Features of JAVA
Simple
Secure
Portable
Object-oriented
Robust
Multithreaded
Architecture-neutral
Interpreted
High performance
Distributed
Dynamic
James Gosling initiated Java language project in June 1991 for use in one of his many
set-top box projects. The language, initially called ‗Oak‘ after an oak tree that stood
outside Gosling's office, also went by the name ‗Green‘ and ended up later being
renamed as Java, from a list of random words.
Sun released the first public implementation as Java 1.0 in 1995. It promised
Write Once, Run Anywhere (WORA), providing no-cost run-times on popular
platforms.
On 13 November, 2006, Sun released much of Java as free and open source software
under the terms of the GNU General Public License (GPL).
On 8 May, 2007, Sun finished the process, making all of Java's core code free and
open-source, aside from a small portion of code to which Sun did not hold the
copyright.
Two Paradigms of Programming
All computer programs consist of two elements: code and data.
Abstraction
An essential element of object-oriented programming is abstraction. It focuses on
hiding the implementation details of an object and exposing only the essential
features.
Three OO Concepts:
Encapsulation
Inheritance
Polymorphism
Encapsulation
It is one of the core concepts of Object Oriented Programming (OOP) in which we
bind the data members and methods into a single unit .Specifically, the data defined
by the class are referred to as member variables or instance variables. The code
that operates on that data is referred to as member methods or just methods.
Inheritance
Inheritance is the process by which one object acquires the properties of another
object. This is important because it supports the concept of hierarchical classification.
The class which inherits the properties of other is known as subclass (derived class,
child class) and the class whose properties are inherited is known as superclass (base
class, parent class).
Polymorphism
It is a feature that allows one interface to be used for a general class of actions.
Polymorphism in java is a concept by which we can perform a single action by
different ways. Polymorphism is derived from 2 Greek words: poly and morphs. The
word "poly" means many and "morphs" means forms.
There are two types of polymorphism in java:
Java Basics
Object - Objects have states and behaviours. An object is an instance of
a class. Example: A dog has states - colour, name, breed as well as
behaviour such as wagging their tail, barking, eating.
Instance Variables - Each object has its unique set of instance variables.
An object's state is created by the values assigned to these instance
variables.
This line outputs the string ―This is a simple Java program.‖ followed by a new line
on the
screen. In this case, println( )displays the string which is passed to it.
System is a predefined class that provides access to the system, and out is the output
stream that is connected to the console.
Output:
1. Whitespace: Java is a free-form language. This means that you do not need to
follow any special indentation rules. In Java, whitespace is a space, tab, or
newline.
2. Identifiers: Identifiers are used for class names, method names, and variable
names. An identifier may be any descriptive sequence of uppercase and lowercase
letters, numbers, or the underscore and dollar-sign characters.
They must not begin with a number, lest they be confused with a numeric literal.
Again, Java is case-sensitive, so VALUE is a different identifier than Value.
5. Separators: In Java, there are a few characters that are used as separators. The
most commonly used separator in Java is the semicolon. Other separators are (),
{},[], etc
6. Keywords: There are 67 keywords currently defined in the Java language. keywords
cannot be used as identifiers
Data Default
Type Range size
Boolean False/ true 1 bit
Char 0-65536 2 byte
Byte –128 to 127 1 byte
Short –32,768 to 32,767 2 byte
Int –2,147,483,648 to 2,147,483,647 4 byte
–9,223,372,036,854,775,808 to
Long 9,223,372,036,854,775,807 8 byte
Integers: This group includes byte, short, int, and long, which are for whole valued signed
numbers. All of these are signed, positive and negative values. Java does not support
unsigned, positive-only integers.
Floating point: This group includes float and double, which represent numbers with
fractional precision.
Char: This group includes char, which represents symbols in a character set, like
letters and numbers.
Boolean This group includes boolean, which is a special type for representing
true/false values.
BYTE: The smallest integer type is byte. This is a signed 8-bit type that has a range
from –128 to 127. Variables of type byte are especially useful when you’re working
with a stream of data from a network or file. They are also useful when you’re
working with raw binary data that may not be directly compatible with Java’s other
built-in types.
SHORT: 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.
Output would be
Value of char variable ch1 is :a
Value of char variable ch2 is :A
VARIABLES
The variable is the basic unit of storage in a Java program. A variable is defined by
the combination of an identifier, a type, and an optional initializer.
Declaring a Variable
Local Variables
Dynamic Initialization
Java allows variables to be initialized dynamically, using any expression valid
at the time the variable is declared.
Ex:
class dyn {
public static void main(String args[]) {
double a = 3.0, b = 4.0;
// c is dynamically initialized
double c = [Link](a * a + b * b);
[Link]("Hypotenuse is " + c);
}
}
Here, three local variables—a, b, and c—are declared. The first two, a and b, are
initialized by constants. However, c is initialized dynamically to the length of the
hypotenuse
Java allows variables to be declared within any block. A block defines a scope.
Thus, each time you start a new block, you are creating a new scope. A scope
determines what objects are visible to other parts of your program. It also determines
the lifetime of those objects.
In Java, there are two major scopes
1. defined by a class
Example:
class Scope {
public static void main(String args[]) { int x; //
known to all code within main x = 10;
if(x == 10) { // start new scope
int y = 20; // known only to this block
// x and y both known here. [Link]("x and y:
" + x + " " + y); x = y * 2;
}
// y = 100; // Error! y not known here
// x is still known here.
[Link]("x is " + x);
}
}
Output
x and y: 10 20
x is 22
To create a conversion between two incompatible types, you must use a cast. A cast is simply an
explicit type conversion.
Syntax :
(target-type) value
Example:
int a;
byte b;
// …
b = (byte) a
Example:
Output :
Double value 100.04
Long value 100
Int value 100
ARRAYS
One-Dimensional Arrays
A one-dimensional array is essentially, a list of like-typed variables. To create an
array, you first must create an array variable of the desired type. The general form of
a one-dimensional
array declaration is:
datatype identifier [ ];
Or
datatype[ ] identifier;
Multidimensional Arrays
Operators In Java
Java provides a rich operator environment. Java provides a rich set of operators to
manipulate variables. Operators in Java are special symbols that perform operations
on variables and [Link] can divide all the Java operators into the following
groups:
Arithmetic Operators
Relational Operators
Bitwise Operators
Logical Operators
Ternary Operator
Assignment Operator
Operators Precedence
Postfix expr++ expr--
Unary ++expr --expr +expr -expr ~ !
Multiplicative */%
Additive +-
Shift << >> >>>
Relational < > <= >= instance of
Equality == !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
Ternary ?:
Arithmetic Operators
The basic arithmetic operations—addition, subtraction, multiplication, and
division—all behave as you would expect for all numeric types.
The unary minus operator negates its single operand.
The unary plus operator simply returns the value of its operand.
class OperatorExample{
public static void main(String args[]){ int a=10;
int b=5;
[Link](a+b);//15
[Link](a-b);//5
[Link](a*b);//50
[Link](a/b);//2
[Link](a%b);//0
}}
Java provides special operators that can be used to combine an arithmetic operation
with an assignment.
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=20;
a+=4; //a=a+4 (a=10+4)
b-=4; //b=b-4
(b=20-4)
[Link](a);
[Link](b);
}}
operator Description
== Check if two operands are equal
!= Check if two operands are not equal.
> Check if operand on the left is greater than operand on the right
< Check operand on the left is smaller than right operand
>= check left operand is greater than or equal to right operand
<= Check if operand on left is smaller than or equal to right operand
The Boolean logical operators shown here operate only on boolean operands and
relational expressions. All of the binary logical operators combine two boolean
values to form a resultant boolean value. The logical Boolean operators, &, |, and ^,
operate on boolean values in the same way that they operate on the bits of an integer.
Java provides two interesting Boolean operators called short circuit operator.
They are called short-circuit because they do not always evaluate both operands—
evaluation stops as soon as the result is determined.
If the first condition is false, Java does not evaluate the second condition because the
result will always be false.
2) || (Short-Circuit OR)
If the first condition is true, Java does not evaluate the second condition because the
result will always be true.
Example:
int a = 5;
int b = 10;
// Short-circuit OR (||)
if (a < 0 || b > 5) {
} }}
The Bitwise Operators
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 of their
operands. bitwise operators work on the binary representation (bits) of integers
They are summarized in the following table:
Operator Description
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
<< left shift
>> right shift
>>> Right Shift zero fill
1 1 0 1 1 0
1 0 0 0 1 1
0 1 1 0 1 1
0 0 1 0 0 0
Example:
public class UnsignedShiftExample {
public static void main(String[] args) {
int positive = 40; // Binary: 00000000 00000000 00000000 00101000
int negative = -40; // Binary: 11111111 11111111 11111111 11011000
class OperatorExample{
public static void main(String args[]){ int
a=2;
int b=5;
int min=(a<b)?a:b;
[Link](min);
}}
Output:
CONTROL STATEMENTS
If- else:
The if statement is Java‘s conditional branch statement. It can be used to route
program execution through two different paths. Here is the general form of the if
statement:
if (condition)
statement1;
else
statement2;
Syntax:
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
.
.
.else statement;
Output : two
Iteration Statements
Java‘s iteration statements are for, while, and do-while. These statements create what
we commonly call loops. As you probably know, a loop repeatedly executes the same
set of instructions until a termination condition is met. As you will see, Java has a
loop to fit any programming need.
while
The while loop is Java‘s most fundamental loop statement. It repeats a statement or
block
while its controlling expression is true. It is also called as Entry Controlled Loop. Here is its
general form:
while(condition)
{
// body of loop
}
The condition can be any Boolean expression. The body of the loop will be
executed as long
as the conditional expression is true. When condition becomes false, control passes
to the next line of code immediately following the loop.
class WhileLoopExample{
public static void main(String[]
args){ int num=0;
while(num<=5){
[Link](""+n
um); num++;
}
}
}
do-while
The do-while loop always executes its body at least once, because its conditional
expression is at the bottom of the loop. It is also called as Exit Controlled Loop. Its
general form is
do {
// body of loop
} while (condition);
For:
There are two forms of the for loop.
The first is the traditional form that has been in use since the original version of
Java. The second is the newer ―for-each‖ form.
Here, type specifies the type and itr-var specifies the name of an iteration
variable that will receive the elements from a collection(array), one at a time,
from beginning to end. The collection being cycled through is specified by
collection.
for(int x : numbers ) {
[Link]( x );
[Link](",");
}
[Link]("\n");
String [] names = {"James", "Larry", "Tom", "Lacy"};
Jump Statements
Using break
In Java, the break statement has three uses. First, as you have seen, it terminates a
statement sequence in a switch statement. Second, it can be used to exit a loop.
Third, it can be used as a ―civilized‖ form of goto.
1) Using break to Exit a Loop
2) Using break as a Form of Goto:
Java does not have a goto statement because it provides a way to branch in an
arbitrary and unstructured manner. This usually makes goto-ridden code hard
to understand and hard to maintain.
Using continue
In while and do-while loops, a continue statement causes control to be transferred
directly to the conditional expression that controls the loop. In a for loop, control goes
first to the iteration portion of the for statement and then to
the conditional expression. For all three loops, any intermediate code is bypassed.
The general form of the labelled break The general form of the labelled
statement is shown here: continue statement is shown here:
break label; continue label;
Return
The last control statement is return. The return statement is used to explicitly return from a
method. That is, it causes program control to transfer back to the caller of the method. As such,
it is categorized as a jump statement.
At any time in a method, the return statement can be used to cause execution to branch
back to the caller of the method. Thus, the return statement immediately terminates the method
in which it is executed.
class Return {
public static void main(String args[])
{
boolean t = true;
[Link]("Before the return.");
if(t)
return; // return to caller
[Link]("This won't execute.");
}
}
The output from this program is shown here:
Before the return.
Here, return causes execution to return to the Java run-time system, since it is the
run-time system that call main ( ):