[go: up one dir, main page]

0% found this document useful (0 votes)
10 views40 pages

Unit Ii

Uploaded by

yugabharath852
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views40 pages

Unit Ii

Uploaded by

yugabharath852
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Course Material

Subject: Java Programming Class: II B.Sc CS A

Semester: III

Unit – II

Title Page No.

2.1. Constants 2
2.2. Variables 4
2.3. Data Types 7
2.4. Operators and Expressions 11

2.5. Decision Making Statements 19


2.6. Loop Statements 26
2.7. Class 36
2.8. Creating Method 39

1
2.1. Constants

• A constant value is the one which does not change during the execution of a program.
• Constants can be of any of the basic data types.

Integer Numeric Constant

• An Integer Numeric Constant is a sequence of digits (combination of 0-9 digits without


any decimal point or without precision), optionally preceded by a plus or minus sign.
• There are 3 types of integer numeric constant
o Decimal integer constants
o Octal integers constants
o Hexadecimal integer constants
• Decimal Integer Numeric Constant: These have no decimal point in it and are either
be alone or be the combination of 0-9 digits. These have either +ve or -ve sign. For
example: 1214, -1321, 10,254, -78, +99 etc.
• Octal Integer Numeric Constant: These consist of combination of digits from 0-7 with
positive or negative sign. It has leading with 0 or 0 (upper or lower case) means Octal
or octal. For example: 0317,003, -045 etc.
• Hexadecimal Integer Numeric Constant: These have hexadecimal data. It has leading
ox, OX, Ox or x, X. These have combination of 0-9 and A-F (a-f) or alone. The letters a-f
or A-F represents the numbers 10-15. For example: 0x232, 0x92, 0xACD, 0xAEF etc.

Floating or Real numeric constants

• Float Numeric Constants consists of a fractional part in their representation; Integer


constants are inadequate to represent quantities that vary continuously. These quantities
are represented by numbers containing fractional parts like 26.082.

2
• Examples of real constants are: 0.0026, -0.97, 435.29, +487.0, 3.4E-2, 4.5E5
• A floating-point constant consists of a sequence of decimal digits, a decimal point, and
another sequence of decimal digits. A minus sign can precede the value to denote a
negative value. Either the sequence of digits before the decimal point or after the decimal
point can be omitted, but not both.

Single Character Constant

• Single Character constants are enclosed between single quotes('). For example, 'a' and
'%' are both character constants. So these are also called single quote character
constant.
• For example: 'a', 'M', '5', '+', '1' etc. are some valid single character constant.

String Character Constant

• A string is a set of characters enclosed in double quotes ("). For example: "Punar
Deep" is a string.
• You must not confuse strings with characters. A single character constant is enclosed
in single quotes, as in 'a'. However, "a" is a string containing only one letter.
• For example: "Dinesh", "Hello", "2013", "2013-2020", "5+3", "?+!" etc. are some valid
string character constant. These are used for printing purpose or display purpose in the
java program's output statements. These can also be used for assigning the string data
to the character (string) type variables.

Backslash Character Constants

• Java Also Supports Backslash Constants those are used in output methods For Example
\n is used for new line Character These are also Called as escape Sequence or backslash
character Constants For Ex: \t For Tab ( Five Spaces in one Time ) \b Back Space etc.

3
2.2. Variables

• Variable is an identifier which holds data or another one variable is an identifier whose
value can be changed at the execution time of program. Variable is an identifier which
can be used to identify input data in a program.

• A variable is a data name that may be used to store a data value.


• A variable may take different values at different time during execution.
• Java variable is a named location in a memory where a program can manipulate the
data, this location is used to hold the value of the variable.
• The value of the java variable may get change in the program.
• Java variable might be belonging to any of the data type like int, float, char etc.
• Variables should be declared in the java program before to use

Rules for naming Java variable:

• Every variable name should start with either alphabets or underscore (_) or dollar ($)
symbol. Note: Actually a variable also can start with ¥,¢, or any other currency sign.(in
advance version of java)
• Variables are case sensitive eg. int var must be used ‘var’ not ‘Var’
• They can be constructed with digits, letters. Eg. var12 or var2 must not be 12var

4
• No space is allowed in the variable declarations.
• Except underscore ( _ ) no special symbol are allowed in the middle of variable
declaration
• Variable name always should exist in the left hand side of assignment operators.
• int Sum, float height, double a_value are some examples for variable name
• White space is not allowed. Eg. int var1 is valid int va r1 is not valid
• Upper case lower cases are significant.
• Maximum length of variable is 64 characters
• No keywords should access variable name.
• Variable initialization means assigning a value to the variable. int a=10;

Variable declarations

• In which sufficient memory will be allocated and holds default values.

Variable initialization

• It is the process of storing user defined values at the time of allocation of memory
space.

5
Variable assignment

• Value is assigned to a variable if that is already declared or initialized.

Over all example

Types of variable

• Type of Variables: There are three (3) types of variables in java:

6
1) Local Variable

• A variable declared inside the body of the method is called local variable. You can use
this variable only within that method and the other methods in the class aren't even aware
that the variable exists.
• A local variable cannot be defined with "static" keyword.

2) Instance Variable

• A variable declared inside the class but outside the body of the method, is called instance
variable. It is not declared as static.
• It is called instance variable because its value is instance specific and is not shared
among instances.

3) Static variable

• A variable which is declared as static is called static variable. It cannot be local. You
can create a single copy of static variable and share among all the instances of the class.
Memory allocation for static variable happens only once when the class is loaded in the
memory.

2.3. Data Types

• Data type is a special keyword used to allocate sufficient memory space for the data, in
other words Data type is used for representing the data in main memory (RAM) of the
computer.

7
Three categories of data types

• Fundamental or primitive data types


• Derived data types
• User defined data types

Primitive data types

• Primitive data types are those whose variables allows us to store only one value but
they never allows us to store multiple values of same type.
• This is a data type whose variable can hold maximum one value at a time.

8
• Here "a" store only one value at a time because it is primitive type variable.

Derived data types

• Derived data types are those whose variables allow us to store multiple values of same
type. But they never allow to store multiple values of different types.
• These are the data type whose variable can hold more than one value of similar type.
In general derived data type can be achieve using array.

• Here derived data type store only same type of data at a time not store integer, character
and string at same time.

User defined data types

• User defined data types are those which are developed by programmers by making use
of appropriate features of the language.
• User defined data types related variables allows us to store multiple values either of same
type or different type or both. This is a data type whose variable can hold more than one
value of dissimilar type, in java it is achieved using class concept.
• Note: In java both derived and user defined data type combined name as reference
data type.
• In C language, user defined data types can be developed by using struct, union, enum
etc. In java programming user defined datatype can be developed by using the features
of classes and interfaces.

In java we have data type which are organized in four groups

o Integer category data types


o Character category data types
o Float category data types
o Boolean category data types

9
Integer category data types

• These category data types are used for storing integer data in the main memory of
computer by allocating sufficient amount of memory space.
• Integer category data types are divided into four types which are given in following table

Character category data types

• A character is an identifier which is enclosed within single quotes. In java to represent


character data, we use a data type called char. This data type takes two byte since it
follows Unicode character set.

Float category data types

• Float category data type are used for representing float values. This category contains
two data types, they are in the given table

Boolean category data types

• Boolean category data type is used for representing or storing logical values is true or
false. In java programming to represent Boolean values or logical values, we use a data
type called Boolean.

10
2.4. Operators and Expressions

• An operator is a symbol that tells the compiler to perform specific mathematical or


logical functions.
• Operators are used in programs to manipulate data and variables.
• Java language is rich in built-in operators and provides the following types of operators
▪ Arithmetic operators
▪ Relational operators
▪ Logical operators
▪ Assignment operators
▪ Increment/decrement operators
▪ Conditional operators (ternary operators)
▪ Bit wise operators

11
Arithmetic Operators

• Java Arithmetic operators are used to perform mathematical calculations like addition,
subtraction, multiplication, division and modulus.
• Given table shows the entire Arithmetic operator supported by Java Language. Let’s
suppose variable A hold 8 and B hold 3.

12
Relational Operators

• Relational operators are used to find the relation between two variables. i.e. to compare
the values of two variables in a java program
• Given table shows the entire relatinal operator supported by Java Language. Let’s
suppose variable A hold 8 and B hold 3.

13
Logical Operators

• These operators are used to perform logical operations on the given expressions.
• There are 3 logical operators in java language. They are, logical AND (&&), logical OR
(||) and logical NOT (!).
• Which can be used to combine more than one Condition?. Suppose you want to
combined two conditions A<B and B>C, then you need to use Logical Operator like (A<B)
&& (B>C). Here && is Logical Operator.

Assignment Operators

• In java programs, values for the variables are assigned using assignment operators.
• Let’s suppose variable A hold 8 and B hold 3.

14
Increment/Decrement Operators

• Increment operators are used to increase the value of the variable by one and decrement
operators are used to decrease the value of the variable by one in C programs.
• Increment / Decrement operator are two types as follows:
o Post increment / decrement
o Pre increment / decrement
• Syntax:
o Increment operator: ++var_name; (or) var_name++;
o Decrement operator: – -var_name; (or) var_name – -;
• Example:
o Increment operator : ++ i ; i ++ ;
o Decrement operator : – – i ; i – – ;

15
Conditional Operators (Ternary Operators)

• Conditional operators return one value if condition is true and returns another value is
condition is false.
• This operator is also called as ternary operator.
• Syntax : (Condition? true_value: false_value);
• Example : (A > 100 ? 0 : 1);

16
Bit Wise Operators

• These operators are used to perform bit operations. Decimal values are converted into
binary values which are the sequence of bits and bit wise operators work on these bits.
• Bit wise operators in java language are & (bitwise AND), | (bitwise OR), ~ (bitwise OR),
^ (XOR), << (left shift) and >> (right shift).

17
18
2.5. Decision Making Statements

• Decision making structures require that the programmer specifies one or more conditions
to be evaluated or tested by the program, along with a statement or statements to be
executed.
• if the condition is determined to be true, and optionally, other statements to be executed
if the condition is determined to be false.

Types of Decision Making Statements

o Simple if statement
o If else statement
o Nested If-else statement
o Switch statement
o Conditional or Ternary operator statement

Simple If Statement

• The if statement is powerful decision making statement and is used to control the flow
of execution of statements.
• It allows the computer to evaluate the expression first and then, depending on whether
the value of the expression is ‘true’ or ‘false’, it transfer the control to a particular
statement.
• An if statement consists of a Boolean expression followed by one or more statements
• If the expression is true, then 'statement-inside' it will be executed, otherwise 'statement-
inside' is skipped and only 'statement-outside' is executed.

19
If else statement

• An if statement can be followed by an optional else statement, which executes when


the Boolean expression is false.
• If the Boolean expression evaluates to true, then the if block will be executed,
otherwise, the else block will be executed.

20
21
Nested if...else statement

• The if...else statement executes two different codes depending upon whether the test
expression is true or false. Sometimes, a choice has to be made from more than 2
possibilities.
• The nested if...else statement allows you to check for multiple test expressions and
execute different codes for more than two conditions.

22
• if 'expression' is false the 'statement-block3' will be executed, otherwise it continues to
perform the test for 'expression 1' . If the 'expression 1' is true the 'statement-block1' is
executed otherwise 'statement-block2' is executed.

Switch Statement

• Switch statement is used to solve multiple option type problems for menu like program,
where one value is associated with each option.
• The expression in switch case evaluates to return an integral value, which is then
compared to the values in different cases, where it matches that block of code is
executed, if there is no match, then default block is executed.
• The general form of switch statement is,

23
• The expression is an integer expression or character value1, value-2 ----- are constants
or constant expressions

24
• You can have any number of case statements within a switch. Each case is followed by
the value to be compared to and a colon.
• When the variable being switched on is equal to a case, the statements following that
case will execute until a break statement is reached
• When a break statement is reached, the switch terminates, and the flow of control jumps
to the next line following the switch statement.
• Not every case needs to contain a break. If no break appears, the flow of control will fall
through to subsequent cases until a break is reached
• A switch statement can have an optional default case, which must appear at the end of
the switch. The default case can be used for performing a task when none of the cases
is true. No break is needed in the default case.

The ?: operator or Conditional or Ternary operator

• Conditional operators return one value if condition is true and returns another value is
condition is false.
• The conditional operator (? :) is a ternary operator (it takes three operands). The
conditional operator works as follows:

• Where
o expression1 is Condition
o expression2 is Statement Followed if Condition is True
o expression2 is Statement Followed if Condition is False

25
2.6. Loop Statements

• Execution of a statement or set of statement repeatedly is called as looping.


• The loop may be executed a specified number of times and this depends on the
satisfaction of a test condition.
• A program loop is made up of two parts one part is known as body of the loop and the
other is known as control condition.
• Depending on the control condition statement the statements within the loop may be
executed repeatedly.
• Depending on the position of the control statement in the loop, a control structure may
be classified either as an
o Entry controlled loop
o Exit controlled loop

Entry Control Loop

• Entry controlled loop, the condition is tested before the execution of the loop. If the test
condition is true, then the loop gets the execution, otherwise not.

Exit Control Loop

• The types of loop where the test condition is stated at the end of the body of the loop,
are know as the exit controlled loops.
• In the case of the exit controlled loops, the body of the loop gets execution without
testing the given condition for the first time.

26
• Then the condition is tested. If it comes true, then the loop gets another execution and
continues till the result of the test condition is not false.

Block diagram of entry control loop exit control loop

• In Java the Looping Statements are


o For loop
o While Loop
o Do...While Loop

For Loop

• for loop is used to execute a set of statements repeatedly until a particular condition is
satisfied. we can say it an open ended loop.

27
• Initialization: This step is execute first and this is execute only once when we are
entering into the loop first time. This step is allow to declare and initialize any loop control
variables.
• Condition: This is next step after initialization step, if it is true, the body of the loop is
executed, if it is false then the body of the loop does not execute and flow of control goes
outside of the for loop.
• Increment or Decrements: After completion of Initialization and Condition steps loop
body code is executed and then Increment or Decrements steps is execute. This
statement allows to update any loop control variables.

28
29
While Loop

• In while loop first check the condition if condition is true then control goes inside theloop
body otherwise goes outside of the body. while loop will be repeats in clock wise direction.
• While loop can be addressed as an entry control loop. It is completed in 3 steps
o Variable initialization.( e.g int x=0; )
o condition( e.g while( x<=10) )
o Variable increment or decrement ( x++ or x-- or x=x+2 )

• The while loop evaluates the test expression.


• If the test expression is true (nonzero), codes inside the body of while loop is evaluated.
Then, again the test expression is evaluated. The process goes on until the test
expression is false.
• When the test expression is false, the while loop is terminated.

30
31
Do..While Loop

• In some situations it is necessary to execute body of the loop before testing the condition
• Such situations can be handled with the help of do-while loop.
• do statement evaluates the body of the loop first and at the end, the condition is checked
using while statement (or) The do..while loop is similar to the while loop with one
important difference is the body of do...while loop is executed once, before checking the
test expression. Hence, the do...while loop is executed at least once.

32
• The code block (loop body) inside the braces is executed once
• Then, the test expression is evaluated. If the test expression is true, the loop body is
executed again. This process goes on until the test expression is evaluated to 0 (false).
• When the test expression is false (nonzero), the do...while loop is terminated.

Jump in Loops

• Sometimes, while executing a loop, it becomes necessary to skip a part of the loop or
to leave the loop as soon as certain condition becomes true, that is called jumping out
of loop.
• The types of jump in loops are
o Continue
o Break

Continue

• Continue statement is mostly used inside loops. Whenever it is encountered inside a


loop, control directly jumps to the beginning of the loop for next iteration, skipping the
execution of statements inside loop’s body for the current iteration
• The continue statement works somewhat like the break statement. Instead of forcing
termination, it forces the next iteration of the loop to take place, skipping any code in
between.

33
• Syntax Continue;

34
APT
Break

• When break statement is encountered inside a loop, the loop is immediately exited and
the program continues with the statement immediately following the loop
• When a break statement is encountered inside a loop, the loop is immediately
terminated and the program control resumes at the next statement following the loop.
• It can be used to terminate a case in the switch statement Syntax break;

36
APT

2.7. Class

• The classes are the most important feature of java that leads to Object Oriented
programming.
• Class is a user defined data type, which holds its own data members and member
functions, which can be accessed and used by creating object of that class.
• The variables inside class definition are called as data members and the functions are
called member functions
• A class definition starts with the keyword class followed by the class name; and the
class body, enclosed by a pair of curly braces.
• A class definition must be followed either by a semicolon or a list of declarations.
• For example, we defined the Box data type using the keyword class as follows:

• A class can have any number of methods to access the value of various kinds of
methods. In the above example, barking(), hungry() and sleeping() are methods.

Objects

• Once a class is defined, you can declare objects of that type. The syntax for declaring a
object is the same as that for declaring any other variable.
• Objects are instances of class, which holds the data variables declared in class and the
member functions work on these class objects.
• To use the data and access functions defined in the class, you need to create objects.

37
APT
• The new keyword is used to allocate memory at run time. All objects get memory in
Heap memory area.
• Creating multiple objects by one type only

Method in Java

• In java, a method is like function i.e. used to expose behavior of an object.


• Advantage of Method
o Code Reusability
o Code Optimization

38
APT

39
APT
2.8. Creating Method

• A Java method is a collection of statements that are grouped together to perform an


operation.
• When you call the System.out.println() method, for example, the system actually
executes several statements in order to display a message on the console.

Method declaration has four major parts

• The name of the method (method name)


• The type of the value method returns (return type)
• A list of parameters (parameter list)
• A body of the method

Method Calling

• By using a method-name, it should be called.


• There are Two ways in which a method is called
o Method returns a value
o Method returning nothing (no return value)
• The process of method calling is simple. When a program invokes a method, the program
control gets transferred to the called method. This called method then returns control to
the caller in Two Conditions, when

40
APT
o The return statement is executed.
o It reaches the method ending closing brace

41

You might also like