1 of 44

Std: 12th Science

English Medium

Subject: Computer

2 of 44

Java Basics

Chapter-7

3 of 44

Introduction to Java

  • Java is an object-oriented programming language developed by Sun Microsystems in 1991, a company best known for its high-end Unix workstations.
  • Java is small, fast, efficient and easily portable to a wide range of hardware devices.
  • Java differs from C language in terms of object-oriented programming technique.
  • Java includes a set of class libraries that provide basic data types, system input and outpu8t capabilities and other utility functions.
  • These basic classes are part of the Java Development Kit(JDK).
  • Java is platform independent at both the source and the binary level.

4 of 44

  • The program created in any computer programming language using English words is known as source code.
  • Computer understands only machine language also known as object code written in binary form.
  • After writing program in any computer language, we need to convert it into machine understandable code. Ie. Object code.
  • There are 2 techniques use for this: Compilation and Interpretation.
  • The object code is distributed among users for installation of a software because it is not human understandable.
  • So in a license software it is not possible to make changes in a program.

main()

{

}

Source code

object code

Compiler

Interpreter

5 of 44

Java Platform-independent

  • Java uses both compiler and interpreter.

Java

Source

Java

Compiler

Java

Bytecode

Java

Interpreter

For Linux

Java

Interpreter

For windows

Java

Interpreter

For Max

  • Java is platform-independent at both source and binary level.
  • Platform independence is a program’s capability of being moved easily from one computer system to another.

  • At source level, Java’s primitive data types have consistent sizes across all platforms.
  • At binary level, platform-independence is possible due to bytecode interpreter.

6 of 44

  • Programs written in Java are compiled into
  • machine language for a computer that does not
  • really exist.
  • This so-called “virtual” computer is known as the
  • Java Virtual Machine(JVM).
  • The machine language for the Java virtual machine is called Java bytecode.
  • Different Java bytecode interpreter is needed for each type of computer.
  • Java binary files are actually in a form called bytecodes that is not specific to any one processor or any operating system.
  • The disadvantage of using bytecode 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.

Java

Source

Java

Compiler

Java

Bytecode

Java

Interpreter

For Linux

Java

Interpreter

For windows

Java

Interpreter

For Max

7 of 44

Creating Simple Java Application

  • A Java program is composed of classes.
  • It should have atleast one class and it must have main method in it.
  • The extension of a Java source program must be .java.
  • Java program can be created using any ASCII text editor. �For example Windows Notepad.
  • The name of Java program must be the same name as the class name they define and it is case sensitive.
  • If the class that we are going to create contains CallCost name then the file name must be CallCost.java.
  • After creating source file we must compile it in order to create a Bytecode object file having .class extension.
  • To compile the program from command prompt the command is javac. For example: javac CallCost.java It creates .class file.
  • After creating object file the program can be executed using java command. For example: java CallCost

8 of 44

Creating Simple Java Application

//**

* First program to calculate cost */

public class CallCost

{

public static void main(String[] args)

{

/* Declare variable*/

double balance;

double rate;

double duration;

double cost;

balance = 170;

rate = 1.03;

duration = 37;

Cost = duration * rate;

balance = balance – cost;

System.out.print(“Call Duration:”)

System.out.print(duration);

System.out.print(“Seconds”);

System.out.println(“Balance: “ + balance + “Rs”);

}

}

9 of 44

Program Illustration

  • Here the class name is: CallCost
  • The body of a program is contained in a routine called main()
  • In Java main() is the first routine that is run when the program is executed.
  • The text written after // and /* */ are comments.
  • Variables are declared using data type followed by variable name. For eg. double balance
  • The entire program is written inside a class named CallCost.
  • Semi colon (;) is a must after each and every Java Statement.
  • main() function: public static void main(String[] args)
  • System.out.print() or System.out.println() are for printing.

10 of 44

Structure of a Java Program

public static <class-name>

{

<Optional-variable-declarations-and-methods>

public static void main(String[] args)

{

<Statements>

}

<Optional-variable-declarations-and-methods>

}

< and > is used as placeholder that describes something actual we need to type while writing actual program.

11 of 44

Important terms

Data types

Variables

Literals

Comments

Java Statements and expressions

Arithmetic Operators

Comparison Operators

Logical Operators

12 of 44

Data Types

Data type determines the required memory size, type of value, range of values and type of operations that can be performed.

Java supports 8 primitive data types that handle common type of integers, floating point numbers, characters and Boolean values. (true or false)

These types are : byte, short, int, long, float, double, char, boolean.

The first four types hold integer values, next two hold real values, character holds single character from unicode character set and boolean holds either true or false.

13 of 44

Data Types

Data type

Storage space

Type of value

Range of values

Default

value

byte

1 byte

Integer

-128 to 127

0

short

2 bytes

Integer

-32767 to 32768

0

int

4 bytes

Integer

-2147483648 to

2147483647

0

long

8 bytes

Integer

-9223372036854775808 to

9223372036854775807

0

float

4 bytes

Real

10+38 with about 7

Significant digits

0

double

8 bytes

Real

10+308 with about 7

Significant digits

0

char

2 bytes

Character

16-bit Unicode Character

0

boolean

1 byte

Boolean

True, False

False

14 of 44

Integer Numbers:

Integer numbers with b bits precision store signed values in the range of : -2b-1 to 2b-1 -1

For eg. If b = 8 then

= -(2b-1)

= -(28-1)

= -(27)

= -(2*2*2*2*2*2*2)

= -128

Range: -128 to 127

For eg. If b = 16 then

= -(2b-1)

= -(216-1)

= -(215)

= -128

Range: -32768 to 32767

For unsigned values: (0 to 2b-1-1)

For eg. If b = 8 then

= (2b-1)

= (28-1)

= (27)

= (2*2*2*2*2*2*2)

= 128

Range: 0 to 127

15 of 44

Real numbers in Java are compliant with IEEE 745 an international standard.

IEEE means Institute of Electrical and Electronic Engineers.

Java uses Unicode character set.

The char type has 16 bits of precision and is unsigned.

Unocide allows thousands of characters from many different languages and different alphabets

To store data ASCII-7 was used in the beginning.

ASCII-8 was introduced to increase character set.

Multimedia computers now-a-days use Unicode system.

Boolean is not a number, nor can it be tread as one.

It contains either true or false.

16 of 44

Variables:

If we want anything to be remembered by the computer during the program execution, then it needs to be stored in the memory of a computer.

In short variables get stored in RAM and Files get stored in Hard Disk.

A name used to refer to the data stored in memory is called a variable. It can store a piece of data.

<type-name> (variable-names)

For eg. int marks; 🡪 marks is variable, int is data type

Float rate;

Double interest=12.5;

17 of 44

Variable name rules:

Variable name must begin with an alphabet, Underscore(_) or dollar($).

After first character, it may contain digits, alphabets, $ and Underscore character (_)

No space are allowed in variable name.

Legal variable names: birth_date, result, amount$

Illegal names: 4me, %discount

It con not be on the name of reserved words like int, if.

When a variable name includes several words, capitalize the first alphabet of each word, except the first word.

For eg. balanceAmount, birthDate.

This is known as camel case.

18 of 44

Literals

A name used for a constant value is known as Literal.

There are some different kinds of literals

Numeric Literals

Character Literals

String Literals

Boolean Literal

19 of 44

Numeric Literals

Tow types of numeric literals: (1) Integer (2) Real

Integer Literal:

(1) Decimal Literal: For ex: 345 , -98

A decimal literal larger than int is automatically of type long.

We can force a smaller number to be a long by appending an L or l as a suffix. For ex: 4L.

(2) Octal Literal:

Octal numbers are from 0 to 7.

In java a numeric literal with a leading 0(zero) is interpreted as an octal number. For ex: 045.

20 of 44

Numeric Literals

Integer Literal:

(3) Hexa Decimal Literal:

Hexadecimal numbers are from 0 to 9 and A to F.

A to F represents 10 to 15 respectively.

In java a numeric literal with a leading 0x or 0X is interpreted as an Hexadecimal number. For ex: 0xA67.

(4) Binary Literal:

Java also supports binary numbers, using the 0 and 1 with the prefix 0b or 0B.

For ex: 0b10101

21 of 44

Numeric Literals

Real number literals:

Real number literals are also called floating point literals.

These numbers can be represented using two types of notations: Standard and Scientific

In scientific notation, a number is followed by letter e or E and a signed integer exponent.

For ex: 1.2e15

22 of 44

Operators

  • Operators are special symbols used to build an expression.
  • Java supports many different types of operators.

    • Arithmetic Operators
    • Comparison Operators
    • Logical Operators
    • Conditional Operator
    • Assignment Operator

23 of 44

Arithmetic Operators

  • Arithmetic operators are…….
    • Addition +
    • Subtraction –
    • Multiplication *
    • Division /
    • Modulus % : Returns remainder as anser.
      • 8 % 3 🡪 returns 3
      • 25.8 % 7 🡪 returns 4.8
  • All these operators are binary operators.
  • They take two operands.
  • Operators + and – are used as unary operators also.
  • All the above operators can be applied on any data type like byte, short, int, long, float, double.
  • They can also be used for values of char type.

24 of 44

    • When both operands are of same data type, the data type of result is same as the type of operands.
    • If both the operands are integers, result is an integer.
      • 9 / 2 🡪 4 Here integer division results into integer and remainder � is discarded.
      • 8 % 3 🡪 returns 3
    • If both operands are float, result is float.
      • 9f / 2f 🡪 4.5
    • When both operands are of different data type then….
      • Lower range data type is implicitly converted to higher data type. This is known as promotion.
      • At last the result of an expression will be same as higher data range operand.
        • 4 + 3.4 🡪 7.5
        • 9 / 2.0 🡪 4.5

25 of 44

    • With modulus operator %, if first operand is negative, result is negative.

    • In Java % operator can be used with floating point data type also.

    • The result is the remainder after integer quotient.
      • 25.8 % 7 🡪 4.8

    • Operator + can also be used to concatenate a string.
    • When operator + is applied with one of the operand of type string, other operand is automatically converted into string type.

    • Floating point literal is by default of double type and so f suffixed with literals 12.5

26 of 44

Unary Operators

  • Unary operators ++ and – are also called increment and decrement operators respectively.
  • ++ adds 1 to a variable. 🡪 a++
  • -- subtracts 1 to a variable. 🡪 b--

  • a++ 🡪 Post increment operator.
  • ++a 🡪 Pre increment operator.
  • a-- 🡪 Post decrement operator.
  • --a 🡪 Pre decrement operator.
  • In post increment or decrement the older value of variable is used while evaluating the expression.
  • In pre increment or decrement the variable’s value is incremented or decremented first and then the expression is evaluated.

27 of 44

Unary Operators

  • If a = 5 and b = 8 then
    • c = a++ + b++;
      • c= 13 a=6 b=9
    • c = ++a + b--;
      • c= 14 a= 6 b= 7
    • c = --a + ++b;
      • c= 13 a= 4 b= 9
    • c = a-- - --b;
      • c= -2 a= 4 b= 7
    • c = a++ - --b;
      • c= -2 a= 6 b= 7
    • c = ++a - --b;
      • c= -1 a= 6 b= 7

28 of 44

Comparison Operators

  • Comparison operators are also known as relational operators.
  • a == b 🡪 Is a “equal to” b?
  • a != b 🡪 Is a “Not equal to” b?
  • a < b 🡪 Is a “Less than” b?
  • a > b 🡪 Is a “Greater than” b?
  • a <= b 🡪 Is a “Less than or equal to” b?
  • a >= b 🡪 Is a “Greater than or equal to” b?

  • Operators == and != can also be used to compare boolean values.

29 of 44

Logical Operators

  • Logical operators are: AND, OR, XOR and NOT.
  • AND 🡪 &&
  • OR 🡪 ||
  • XOR 🡪 ^
  • NOT 🡪 !

  • A && B 🡪 AND returns true if both the operands are true.
  • A || B 🡪 OR returns false if both the operands are false.
  • A ^ B 🡪 XOR returns true if both the operands are � different(one is true and other is false).
  • !A 🡪 Returns true if A is false.

30 of 44

Short circuiting

  • While using logical operators AND and OR, Java does not evaluate the second operand unless it is necessary to resolve the result.

  • If first operand is false in case of AND(&&), no need to evaluate second operand.

  • Similarly if first operand is true in case of OR(||), no need to evaluate second operand.
    • For ex: expression (x != 0) && (y/x>1).
    • If first is false(x is zero) then there is no need to evaluate second operand(y/x > 1). This is called short circuiting. Without short circuiting it would have resulted into division by zero error.

31 of 44

Conditional Operator

  • Conditional operator is also known as ternary operator that uses 3 operands.

  • ?: is known as conditional operator.
    • <boolean-expression> ? <expression1>:<expression2>

  • The first one is boolean expression and is evaluated first.
  • If its value is true then, value of the entire expression is the value of second operand expression1.
  • If its value is false then, value of the entire expression is the value of third operand expression2.
    • For ex: next = (N % 2 == 0 ) ? (N / 2) : (3 * N + 1);

32 of 44

Assignment Operator

  • = sign is known as assignment operator.
  • Once a variable is declared, we can assign a value to that variable using assignment operator.
    • <variable> = <expression>;
      • Where <expression> represents anything that refers to or computes a data value.

  • In an expression containing assignment statement, evaluation starts from right to left.
  • The right side of = sign is evaluated first and then put the resulting data into the variable situated on the left side of the = sign.
    • For ex: x = 50;

33 of 44

Shorthand assignment operator

  • Java supports shorthand version of assignment.

  • It saves typing time.

Assignment Shorthand Assignment

  • a = a + 1 or a+=1;
  • a = a + b or a+=b;
  • q = q && p or q&&=p;

34 of 44

Typecast

  • In some cases, we may want to force a conversion that wouldn’t be done automatically.
  • Type cast can be used for this.
  • A type cast is indicated by putting a type name in parentheses before the value we want to convert.
    • (<data type>) <expression>

    • For ex:
    • Int a; short b;
    • a = 17; b = (short) a;
  • Variable a is explicitly converted using type cast to a value of type short.

35 of 44

Precedence Order

  • When two operators having different priority, then an operator with the higher precedence is operated first.
  • For ex: in expression a + b * c, multiplication is having higher precedence than addition.
  • So b * c is evaluated first and then the result is added to a.

Associativity

    • When two operator with the same precedence appear in an expression, the expression is evaluated according to its associativity.
    • Associativity determines the direction. (Left to right or Right to Left)
    • In most cases the associativity is from left-to-right. For unary and assignment the associativity is from right-to-left.

36 of 44

Operations

Operators

Associativity

Unary operations

++, --, type cast

Right-to-left

Multiplication, Division, Modulus

*, ?, %

Left-to-Right

Addition , Subtraction

+ , -

Left-to-Right

Relational operators

< , > , <=, >=

Left-to-Right

Relational operators

== , !=

Left-to-Right

Logical AND

&&

Left-to-Right

Logical OR

||

Left-to-Right

Conditional Operator

?:

Right-to-left

Assignment Operator

= , +=, -=, *=, /=, %=

Right-to-left

37 of 44

Control structure

  • In general statements are executed sequentially. One by one.
  • Sometimes program logic need to change the flow of this sequence.
  • The statements that enable to control the flow of execution are known as control structures.
  • There are two types of control structures:
    • Branches
    • Loops
  • Branches are used to choose among two or more possible courses of action. It is also known as selective structures.
  • Loops are used to repeat a sequence of statements over and over until some condition occurs.

38 of 44

Branches

  • Block
  • if statement
  • switch case statement

  • Branches are also known as conditional statements except block.

39 of 44

Block

  • A block statement is a group of statements enclosed between a pair of curly brackets “{“ and “}”.

Format:

{

<statements>

}

Purpose of block:

To group a sequence of statements into a unit that can be treated as single statement.

To group logically related statements.

To create variables with local scope for statements within a block.

40 of 44

To create variables with local scope.

  • A variable declared inside block is known as local variable.
  • The scope of a local variable is limited to the block where they declared inside.
  • When we declare a variable inside block, it is local variable and such variable will cease to exist after the block.
  • For ex:

Blk1:

{

int temp;

temp = x;

x = y;

y = temp;

}

A block can also be labeled by a name. For ex: blk1 here.

41 of 44

Variable conflict

42 of 44

Understanding variable’s scope

43 of 44

if statement

  • It enables to take one of two alternative courses of action depending on whether the value of given boolean-valued expression is true or false.
  • If is also known as branching, or decision or selective control structure.

Structure of if statement:

If(<boolean-expression>)

{

<stetement-1>;

}

else

{

<statement-2>;

}

When if statement is executed, it first evaluates boolean expression.

If its value is true, it executes statement-1.

Otherwise it executes statement-2 written after else.

There can be several statements

44 of 44

if statement