Chapter 7 Weightage
Java Basics 12 marks
Introduction to Java
▪ Java is an object-oriented programming language developed at Sun Microsystems, a
company a best known for its high-end Unix workstations, in 1991.
▪ Modeled after c++, the java language was designed to be small, simple, fast, efficient
and portable across platform and operating systems.
▪ Java is considered as one of the ideal language for distributing executable programs via
the WWW and also general purpose programming language for developing programs
that are easily usable and portable across different platforms.
JDK
▪ JDK is used to develop and run Java program
▪ Java includes a set of class libraries that provide basic data types, system input and output
capabilities, and other utility functions.
▪ These Basic classes are part of the Java Development Kit (JDK).
▪ JDK has classes to support networking, common internet protocols and user
interface toolkit functions.
JAVA IS PLATFORM INDEPENDENT
▪ Platform independence is a program’s capability of being moved easily from one computer
system to another.
▪ Java is platform independent at both the source and the binary level.
▪ At the source level, java’s primitive data types have consistent sizes across all development
platforms.
▪ At binary level, platform independence is possible due to bytecode interpreter.
JVM (Java Virtual Machine ) | Bytecode
▪ Program written in Java are compiled into machine language for a computer that doesn’t
really exist. This is so-called “virtual” computer is known as the Java Virtual Machine
(JVM)
▪ The machine language for the java virtual machine is called Java Bytecodes.
▪ Different java bytecode interpreter is needed for each type of computer.
Advantage - Platform independent - Java binary files are actually in a form called
bytecodes that is not specific to any one processor or any operating system.
The only disadvantage of using bytecodes is its slow execution speed.
▪ There are tools available to convert java bytecodes into native code. Native code is faster
to execute, but then it does not remain machine independent.
1
Create Java application using SciTE editor
▪ Start SciTE application.
▪ Select File New and type the java program.
▪ To save the file, select File Save with [Link]
▪ Compile source program using Tools Compile (Ctrl+F7)
▪ If the program is compiled without any error, execute it using Tools Go (F5)
Structure Of A Java Program
In Java program, text in angle bracket < and > is used as a place holder.
▪ Java consists of function header and the sequence of statements enclosed between braces
{ and }
public class <class-name>
{
<optional – variable – declarations – and –methods> public static void
main(String [ ] args)
{
<statements>
}
<optional – variable – declarations – and – methods>
}
▪ Java source file & class name must be same
▪ [Link]() and [Link]() both methods are used to display results.
DATA TYPES
▪ Java supports 8 primitive data types.
▪ Data Types – byte (1 byte), short (2 bytes), int(4 bytes), long (8 bytes), float (4 bytes),
double (8 bytes), char (2 bytes), Boolean (1 byte)
2
Variable
▪ A name used to refer to the data stored in memory is called a variable
▪ Syntax <datatype-name> {variable-names};
▪ Example int marks; | float rate; | char grade;
RULES TO DEFINE VARIABLE NAME
▪ It must begin with an alphabet, underscore (_) or dollar sign ($).
▪ No spaces are allowed in variables : birth date, my school project
▪ It cannot be a reserved word : class, public, static,void if etc
▪ Legal variable names : birth_date, result, CallCost, top5students, date, $price
▪ Illegal variable names : 4me, %discount, birth date.
Guidelines for Naming Variables
▪ Choose meaningful variable names. (calculateArea, calculateCallCost)
▪ Java allows variable name of any length.
▪ Separate words with underscore. Ex : birth_date
▪ Java is case-sensitive. So upper case and lower case are considered to be different.
Example variable X is different from the variable x
▪ Names of classes to begin with upper case.
▪ Names of variables and of methods begin with lower case. Referred to as camel
case. Ex : birthDate, callCost
Variable Types
There are 3 kinds of variables :
1) Instance variables
2) Class/Static variables
3) Local variables
class Demo{
public static void main(String args[]){
int age=15; Instance variables
float pi=3.14;
static int count=0; Class variable
void display(){
int total=50; Local variable
[Link](“hello”);
}
}
}
Literals
A name used for a constant value is known as literal. Different kinds of literals in Java for
number, character, string and Boolean values.
3
Comments
▪ Comments in a program are for human readers only
▪ Comments are entirely ignored by the computer. They are not compiled or interpreted in
java
Java supports 3 types of comments :
1) Single line comment //
All the text up to the end of the line is ignored.
2) Multi line comment /*......*/
Comments cannot be nested (comment inside a comment)
3) Documentation comment /** ..... */
(creating API documentatio from the code, javadoc system)
Expression
▪ The basic building blocks of expressions are literals, variables and functi n calls.
▪ More complex expressions can be built up by using operators to combine simpler
expression.
▪ Operators include arithmetic operators (+, -, *, /, %), comparison operators (>, <, =,
…), logical operators (and, or, not…)
A+B* C (A + B) * C
4
Operators
▪ Operators are special symbols used to build an expression.
1.
Arithmetic Operators
5. 2.
Assignment operator Comparison operators
Operators
4.
3. Logical Operators
Con ditional
erat
opors
Arithmetic Operator
Basic arithmetic operators are +, -, *, /, %(modulus)
All these operators are binary, they take 2 operands.
Used for byte, short, int, long, float, double, and char(treated as int).
Arithmetic operation OperatorMeaningEg
+Addition2+8
–Subtraction2-8
*Multiplication2*8
/Division8/2
%Reminder8%3
Increment and Decrement Operator
++& -- is known as unary operators .
++ is increment operator (which adds 1) and -- is Decrement operator(which subtracts 1)
Increment / Decrement Operators
++xpre-increment
--xpre-decrement x++post –increment
x--post-decrement
Comparison Operator
▪ Comparison Operators are known as Relational operators.
▪ The result of expression is Boolean; either true or false.
5
Comparison Operators
Operator Meaning
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
== Equal to
!= Not equal to
Logical Operator
▪ Logical operators known as Boolean Operators.
▪ Logical operators: AND,OR, XOR, (Exclusive OR),NOT.
Logical Operators
Operator Sign Use
AND && Used to combine two values
OR || Used to combine two values
XOR ^ It returns true only if operands are different
NOT ! Operant is true, result is false & vice versa
Conditional Operator
▪ Also known as ternary Operator.
▪ Conditional Operator uses 3 operands.
▪ It uses two symbols ? and : in the expression.
▪ Syntax: (Boolean-expr) ? (expr1) : (expr2)
Assignment Operator
▪ To assign a value to variable by using the assignment operator ‘=’
▪ Syntax : <variable> = <expression>;
▪ Variable on left hand side of expression is lvalue(location in memory)
Block statement
▪ A block statement is a group of statements enclosed between a pair of braces { and }
▪ Block can be used for various purpose as follows:
To group a sequence of statements into a unit that is to be treated as a single
statement.
To group logically related statements.
To create variables with local scope for statements within a block.
6
Control Structures
▪ In general, the statements are executed sequentially, one by one. Sometimes, program logic
needs to change the flow of this sequence.
▪ The statements that enable to control the flow of execution are considered as control
structures
ControlStructures
loops
branches/decision/selective
For loop While loop Do while loop If statement Switch case
Branches (or Decision or selective structure)
Branches are used to choose among two or more possible courses of
action, also called decision or selective structure if(boolean
expression){
(1) IF STATEMENT statement1;
Used in a program to take one of two alternative coursed of action, }
depending upon Boolean valued expression. else{
When if statement is executed, it first evaluates Boolean statement2;
expression }
If its value is true, it executes statement1;
Otherwise it executes statement2 written after keyword else
Switch
(2) SWITCH STATEMENT (expression){
Used when there are many alternative actions to be taken case 1:
depending upon the value of a variable or expression. statement1;
Test expression should be of the type byte, char, short or int break;
This test expression is compared with each of the case values. case 2:
If a match is found, the following statement is executed. statement2;
break; default:
statementN;
If no match is found, the default statement is execute }
Looping (Repetitive Control Structures)
Loops are used to repeat a sequence of statements over and over until some
condition occurs. Loop are executed if condition is true.
Java supports 3 types of looping constructs:
7
Looping
For loop While loop Do while loop
Entry controlled or pre-test Entry controlled or pre test Exit controlled or post-test
Loop constructs. Loop constructs. It is used loop constructs.
It is used when numbers of when number of iterations Statements of loop executed
Iterations are pre-defined. Are not pre-determined. atleast once.
for (initialize; condition; //initialize //initialize
iteration){ while (condition){ Do{
statements; statements; statements;
} incr/decr statement; incr/decr statement;
} } while (condition);
Statement
BREAK STATEMENT for(){
▪ Used to transfer the control outside switch/loop structure. if(condition){
▪ It is used to exit the loop. break;
▪ It is jumps outside the nearest loop containing this statement. }
statementss;
}
CONTINUE STATEMENT
▪ It is used to skip the following statement in a loop and continue with the
for(){
next iteration.
if(condition){
continue;
}
statements;
}