0% found this document useful (0 votes)
40 views70 pages

Unit-Ii Programming Constructs

The document discusses various Java programming constructs including variables, data types, identifiers, naming conventions, keywords, operators, and precedence rules. It defines different types of variables like local, instance, and static variables. It also explains primitive data types, naming rules for identifiers, keywords, and different categories of operators in Java along with their precedence and associativity.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views70 pages

Unit-Ii Programming Constructs

The document discusses various Java programming constructs including variables, data types, identifiers, naming conventions, keywords, operators, and precedence rules. It defines different types of variables like local, instance, and static variables. It also explains primitive data types, naming rules for identifiers, keywords, and different categories of operators in Java along with their precedence and associativity.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 70

UNIT-II

PROGRAMMING CONSTRUCTS
TOPICS
Variables - primitive data types-
identifiers naming conventions -
keywords literals -operators – binary -
unary and ternary expression -
precedence rules and associativity -
primitive type conversion and casting -
flow of control - arrays- command line
arguments
Variables
• A variable is a container which holds the value
while the program is executed. A variable is
assigned with a data type.
• Variable is a name of memory location.
• Three types of variables in java,
1.local
2.instance
3.static
• int num=12345;
class A
{  
int data=50; //instance variable  
static int m=100; //static variable  
void method()
{  
int n=90; //local variable  
}  
}//end of class  
1) Local Variable - A variable declared inside the body
of the method is called local variable. We can use
this variable only within that method. 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

3) Static variable - A variable which is declared as static


is called static variable. It cannot be local. Memory
allocation for static variable happens only once when
the class is loaded in the memory.
Primitive data types
• Data types specify the different sizes and values that
can be stored in the variable

• There are two types of data types in Java,

1.Primitive data types: The primitive data types include


boolean, char, byte, short, int, long, float and double

2.Non-primitive data types: The non-primitive data


types include classes, interfaces and arrays
Data Type Default Value Default size

boolean false 1 bit

char '\u0000' 2 byte

byte 0 1 byte

short 0 2 byte

int 0 4 byte

long 0L 8 byte

float 0.0f 4 byte

double 0.0d 8 byte


Identifiers 

• Identifiers in are symbolic names used for


identification. They can be a class name,
variable name, method name, package name,
constant name, and more

public class Computer


{
public static void main(String args[])
{
System.out.println(“JAVA”);
}
}
Rules for Identifiers 
• A valid identifier must have characters [A-Z] or
[a-z] or numbers [0-9], and underscore(_) or a
dollar sign ($)
• There should not be any space in an identifier
• An identifier should not contain a number at
the starting
• An identifier should be of length 4-15 letters
only
• We can't use the Java reserved keywords as an
identifier such as int, float, double, char, etc
Naming conventions

• Java naming convention is a rule to follow


• But, it is not forced to follow. So, it is known as
convention not rule.
• All the classes, interfaces, packages, methods
and fields of Java programming language are
given according to the Java naming
convention.
• If we fail to follow these conventions, it may
generate confusion or erroneous code.
Naming conventions

Class
• It should start with the uppercase letter.
• It should be a noun such as Color, Button,
System, Thread, etc.
• Use appropriate words, instead of acronyms.

public class Employee  
Naming conventions

Interface
• It should start with the uppercase letter.
• It should be an adjective such as Runnable,
Remote, ActionListener.
• Use appropriate words, instead of acronyms.

interface Printable  
Naming conventions
Method
• It should start with lowercase letter.
• It should be a verb such as main(), print(), println().
• If the name contains multiple words, start it with a
lowercase letter followed by an uppercase letter
such as actionPerformed()
void draw()  
{  
 
}  
Naming conventions

Variable
• It should start with a lowercase letter such as
id, name
• It should not start with the special characters
like & (ampersand), $ (dollar), _ (underscore)
• If the name contains multiple words, start it
with the lowercase letter followed by an
uppercase letter such as firstName, lastName.
• Avoid using one-character variables such as x,
y, z Ex:id
Naming conventions
Package
• It should be a lowercase letter such as java,
lang

• If the name contains multiple words, it should


be separated by dots (.) such as
import java.util;
import java.lang;
Naming conventions
Constant
• It should be in uppercase letters such as RED,
YELLOW
• If the name contains multiple words, it should
be separated by an underscore(_) such as
MAX_PRIORITY
• It may contain digits but not as the first letter.
 
static final int MIN_AGE = 18;  
 
Advantage of naming conventions
• We make our code easier to read by others
• It indicates that less time is spent to figure out
what the code does.
Key rules:
• The name must not contain any white spaces
• The name should not start with special
characters like & (ampersand), $ (dollar), _
(underscore).
Keywords
• keywords are also known as reserved words.
Keywords are particular words which acts as a
key to a code

List of Java Keywords,


• public: It is an access modifier. It is used to
indicate that an item is accessible anywhere. It
has the widest scope among all other
modifiers.
• private: It is an access modifier. It is used to
indicate that a method or variable may be
accessed only in the class in which it is
declared

• protected: It is an access modifier. It can be


accessible within package and outside the
package but through inheritance only. It can't
be applied on the class

• this: it can be used to refer the current object


in a method or constructor
• new: it is used to create new objects

• import: it makes classes and interfaces available


and accessible to the current source code

• if: it tests the condition. It executes the if block


if condition is true

• final: it is used to indicate that a variable holds


a constant value. It is applied with a variable. It
is used to restrict the user
Operators

• Operator  is a symbol which is used to perform


some operations
• Unary Operator
• Arithmetic Operator
• Shift Operator
• Relational Operator
• Bitwise Operator
• Logical Operator
• Ternary Operator
• Assignment Operator
Operator Type Category Precedence
Unary postfix expr++ expr--

prefix ++expr --expr +expr -expr ~
!

Arithmetic multiplicative */%

additive +-

Shift shift << >> >>>

Relational comparison < > <= >= instanceof

equality == !=

Bitwise bitwise AND &

bitwise exclusive OR ^

bitwise inclusive OR |

Logical logical AND &&

logical OR ||

Ternary ternary ?:

Assignment assignment = += -= *= /= %= &= ^= |


= <<= >>= >>>=
Unary Operator
• Unary operators require only one operand. Unary operators are
used to perform various operations.

• incrementing/decrementing a value by one

class OperatorExample
{  
public static void main(String args[])
{  
int x=10;  
System.out.println(x++);
System.out.println(++x); 
System.out.println(x--);
System.out.println(--x);
}
}  
class Incdec
{  
public static void main(String args[])
{  
int a=10;  
int b=10;  
System.out.println(a++ + ++a);//10+12=22  
System.out.println(b++ + b++);//10+11=21  
  }
}  
class Arith
{  
public static void main(String args[])
{  
int a=10;  
int b=5;  
System.out.println(a+b); //15  
System.out.println(a-b); //5  
System.out.println(a*b); //50  
System.out.println(a/b); //2  
System.out.println(a%b); //0  
}
}  
class OperatorExample
{  
public static void main(String args[])
{  
int a=2;  
int b=5;  
int min=(a<b)?a:b;  
System.out.println(min);  
}
}  
Operator Precedence
• Operator precedence determines the order in
which the operators in an expression are
evaluated.

• BODMAS
Operator Type Precedence
Unary expr++ expr--

++expr --expr +expr -expr ~ !

Arithmetic */%

+-

Shift << >> >>>

Relational < > <= >= instanceof

== !=

Bitwise &

Logical &&

||

Ternary ?:

Assignment = += -= *= /= %= &= ^= |= <<=


>>= >>>=
Associativity of Operators in Java
• An expression has two operators with similar
precedence, the expression is evaluated
according to its associativity (either left to
right, or right to left)
Java Operator Precedence and Associativity

Operators Precedence Associativity

postfix increment and ++ -- left to right


decrement

prefix increment and


++ -- + - ~ ! right to left
decrement, and unary

multiplicative */% left to right

additive +- left to right

shift << >> >>> left to right

relational < > <= >= instanceof left to right


equality == != left to right

bitwise AND & left to right

bitwise exclusive OR ^ left to right

bitwise inclusive OR | left to right

logical AND && left to right

logical OR || left to right

ternary ?: right to left

= += -= *= /= %=
assignment &= ^= |= <<= >>= >>>= right to left
Type conversion
• Type casting is a method or process that
converts a data type into another data type in
both ways manually and automatically.

• The automatic conversion is done by the


compiler and manual conversion performed
by the programmer
Data type Storage
• boolean − 1 bit
• byte − 1 byte
• char − 2 bytes
• short − 2 bytes
• int − 4 bytes
• long − 8 bytes
• float − 4 bytes
• double − 8 bytes
• There are two types of type casting,
1.Widening Type Casting
2.Narrowing Type Casting
1.Widening Type Casting :
• Converting a lower data type into a higher one is
called widening type casting. It is also known
as implicit conversion 

• It is done automatically. It is safe because there


is no chance to lose data
byte -> short -> char -> int -> long -> float -
> double
public class TypeCasting  
{  
public static void main(String[] args)  
{  
int x = 7;  
long y = x;  
float z = y;  
System.out.println("Before conversion, int value "+x);  
System.out.println("After conversion, long value "+y);  
System.out.println("After conversion, float value "+z);  
}  
}  
2.Narrowing Type Casting
• Converting a higher data type into a lower one
is called narrowing type casting. It is also
known as explicit conversion .
• It is done manually by the programmer. If we
do not perform casting then the compiler
reports a compile-time error.
• double -> float -> long -> int -> char -> short -
> byte  
public class NarrowingTypeCastingExample  
{  
public static void main(String args[])  
{  
double d = 166.66;  
//converting double data type into long data type  
long l = (long)d;  
//converting long data type into int data type  
int i = (int)l;  
System.out.println("Before conversion: "+d);  
//fractional part lost  
System.out.println("After conversion into long type: "+l);  
//fractional part lost  
System.out.println("After conversion into int type: "+i);  
}  
}  
Flow of control
• if statement
• if-else statement
• if-else-if ladder
• nested if statement
• Switch Statement
• Loop Statement – for ,while ,do-while
• Break Statement
• Continue Statement
if statement

• if statement tests the condition. It executes


the if block if condition is true.
Syntax:
if(condition)
{  
//code to be executed  
}  
public class Age
 {  
public static void main(String[] args)
 {  
   
 int age=20;  
   
 if(age>18)
{  
System.out.print("Age is greater than 18");  
 }  
}  
}  
 if-else Statement
• if-else statement also tests the condition. It
executes the if block if condition is true
otherwise else block is executed.
• Syntax:
if(condition)
{  
}
else
{  
  }  
public class OddEven
 {  
public static void main(String[] args)
 {  
  int number=13;  
 if(number%2==0)
{  
System.out.println("even number");  
}
else
{  
System.out.println("odd number");  
}  
}  
}  
if-else-if ladder Statement

• if-else-if ladder statement executes one condition from multiple statements.


Syntax:

if(condition1)
{  
}
else if(condition2)
{  
  
}  
else if(condition3)
{  
}  
else{  
}  
public class IfElseIfExample {  
public static void main(String[] args) {  
    int marks=65;  
      
    if(marks<50){  
        System.out.println("fail");  
    }  
    else if(marks>=50 && marks<60){  
        System.out.println("D grade");  
    }  
    else if(marks>=60 && marks<70){  
        System.out.println("C grade");  
    }  
    else if(marks>=70 && marks<80){  
        System.out.println("B grade");  
    }  
    else if(marks>=80 && marks<90){  
        System.out.println("A grade");  
    }else if(marks>=90 && marks<100){  
        System.out.println("A+ grade");  
    }else{  
        System.out.println("Invalid!");  
    }  } }
 
Switch Statement

• switch statement executes one statement from multiple


conditions. It is like if – else - if ladder statement
switch(expression)
{
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
default:
}
public class SwitchExample {  
public static void main(String[] args)
 {  
    int number=20;  
    switch(number)
{  
    case 10: System.out.println("10");  
    break;  
    case 20: System.out.println("20");  
    break;  
    case 30: System.out.println("30");  
    break;  
    default:System.out.println("Not in 10, 20 or 30");  
    }  
}  
}  
Loops in Java

• Loops are used to execute a set of


instructions/functions repeatedly when some
conditions become true.

Three types of loops,

• for loop
• while loop
• do- while loop
for loop

• for loop is used to iterate a part of the


program several times. If the number of
iteration is fixed, it is recommended to use for
loop.
for(initialization;condition;incr/decr)
{  
//statement or code to be executed  
}  
for loop
• Initialization: It is the initial condition which is executed
once when the loop starts. we can initialize the variable,
or we can use an already initialized variable. It is an
optional condition.
• Condition: It is the second condition which is executed
each time to test the condition of the loop. It continues
execution until the condition is false.
• Statement: The statement of the loop is executed each
time until the second condition is false.
• Increment/Decrement: It increments or decrements the
variable value. It is an optional condition.
public class ForExample
 {  
public static void main(String[] args)
 {  
        for(int i=1;i<=10;i++)
{  
        System.out.println(i);  
  }  
}  
}  
while loop
• while loop is used to iterate a part of the
program several times. If the number of
iteration is not fixed, it is recommended to use
while loop
while(condition)
{  
//code to be executed  
}  
public class WhileExample
{
public static void main(String[] args)
{
int i=1;
while(i<=10){
System.out.println(i);
i++;
}
}
}
do-while Loop

• do-while loop is used to iterate a part of the


program several times.

• If the number of iteration is not fixed and you


must have to execute the loop at least once, it
is recommended to use do-while loop.
do
{  
//code to be executed  
}while(condition);  
public class DoWhileExample
{
public static void main(String[] args)
{
int i=1;
do
{
System.out.println(i);
i++;
}while(i<=10);
}
}
*
**
***
****
*****
• Print the alphabet a …z
• Print the alphabet z … a
Arrays
• An array is a collection of similar type of
elements which has contiguous memory location

• Java array is an object which contains elements


of a similar data type

• Index-based, the first element of the array is


stored at the 0th index, 2nd element is stored on
1st index and so on
Types of Array 

There are two types of array,


1.Single Dimensional Array
2.Multidimensional Array

1.Single Dimensional Array 


Syntax
dataType[] arr; (or)  dataType arr[];
int a[]={33,3,4,5};  
class Testarray
{
public static void main(String args[])
{
int a[]={33,3,4,5};
for(int i=0;i<a.length;i++)
{
System.out.println(a[i]);
}
}
}
2.Multidimensional Array
Syntax
dataType[][] arrayRefVar; (or)  
dataType arrayRefVar[][];

int[][] arr=new int[3][3];
class Testarray
{
public static void main(String args[])
{
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}
Programs
1.Fibonacci Series
2.Prime Number Program
3.Palindrome Program
4.Factorial Program
5.Armstrong Number
6.Print the duplicate elements of an array
7.Print the largest element in an array
8.Print the smallest element in an array
9.Print the elements of an array present on odd position
10.Find 2nd Largest Number in an Array
11.Print Odd and Even Numbers of an array
import java.util.Scanner;
class Age
{
public static void main(String[] args)
{
Scanner myObj = new Scanner(System.in);
System.out.println("Enter your age :");
int age = myObj.nextInt();
System.out.println("Age is: " + age);

}
}
• compile by > javac  Age.java  

• run by > java  Age
Command line arguments
• It is an argument, that is passed at the time of
running the java program

• The arguments passed from the console can


be received in the java program and it can be
used as an input
class Example
{
public static void main(String args[])
{
System.out.println("Your first argument is:
"+args[0]);
}
}
• compile by > javac Example.java  

• run by > java Example Input
class Cse
{
public static void main(String args[])
{
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
}
}
• compile by > javac Cse.java  

• run by > java Cse welcome 10 a
class Sum
{
public static void main(String ar[])
{
int x,y,s;
x=Integer.parseInt(ar[0]);
y=Integer.parseInt(ar[1]);
s=x+y;
System.out.println("sum of " + x + " and " + y +" is "
+s);
}
}
• compile by > javac  Sum.java  

• run by > java  Sum 10 20

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy