Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 25

1

Introduction to OOP, Procedural Programming Language and Object Oriented Language,


Principles of OOP, Applications of OOP, History of Java, Java features, Java Virtual Machine
(JVM), Java Program Structure, Variables, Primitive data types, Identifiers, Literals – Examples,
Operators, expressions – Examples, Precedence Rules and Associatively, Primitive Type
Conversion and Casting, Flow of Control, Classes and objects, Class Declaration, Creating
Objects, Methods, Method Overloading.

Aim

Object oriented programming aims to implement real world entities like inheritance, hiding,
polymorphism etc in programming. OOP is to bind together the data and the functions that
operate on them so that no other part of code can access this data except that function.

Q1. Object Oriented Programming


Q2. Procedural Programming Language and Object Oriented Language,
Q3. Applications of OOP
Q4. History and features of Java
Q5. Java Virtual Machine (JVM),
Q6. Java Program Structure
Q7. Reserver Wods /Keywords
Q8. Modifiers(Access Specifies)
Q9. Statements & Control Flow Statement
Q10. Primitive data types
Q11. Scope and Life time of Variable
Q12. Variable Type
Q13. Main function
Q14. Include Vs Import
Q15. Identifiers and Literals
Q16. Operators
Q17. Operator Precedence
Q18. Primitive type conversion and casting:
Q19. Control Statements
Q20. Method Overloading
2

Q1. Object Oriented Programming

Oop’s is termed as Object-Oriented Programming language , based on objects and data. All
languages developed from 1990 having object-oriented features. The object-oriented
programming is the most important and powerful way of creating software. C++, Object Pascal,
Java, Python are multi-paradigm programming languages that support object-oriented
programming.

OOP allows decomposition of a problem into a number of elements called objects and then
binds data and function around these objects. The data associated with the function will be
accessed by object associated with that function only. The following figure depicts the objects
communication

Features of object oriented programming are:

• Focus is on data rather than procedure.


• It follows bottom up approach.
• Member Functions operate on the data members of an object are bind together.
• Data is hidden and cannot be accessed by external function.
• Objects may communicate with each other through function.

The object-oriented paradigm deals with active objects instead of passive objects. A file in an
object-oriented paradigm can be packed with all the procedures—called methods in the object-
oriented paradigm—to be performed by the file: printing, copying, deleting and so on. The
program in this paradigm just sends the corresponding request to the object.
3

The structure of the Object oriented program is shown in the below figure:

 Two objects can communicate via the function without knowing the data of each
another.

Concepts of Object Oriented Programming

1. Classes
2. Objects
3. Dynamic Binding
4. Message Passing
5. Inheritance.
6. Abstraction
7. Encapsulation.
8. Polymorphism

Classes : A class is a user defined blueprint from which objects are created.  It represents the
set of member functions and member variables that are common to all objects of one type. In
this figure Flower is class name and it has member functions as Turn() ,Pick() and member
variables as color.
4

Objects: Instance of class is called as object. Objects have states and behaviors. Example: A dog
has states - color, name, breed as well as behaviors – wagging the tail, barking, eating. In the
above diagram d1 is object to Dog class which acts as instance and access the variables and
methods of Dog class

Class

Dynamic Binding:  In JAVA programming language objects are allocated their memory at the
time of execution using the new operator. After allocation of memory the instance variables are
binds with their associated methods at the time of execution. This type of data binding is also
called dynamic binding or late binding or execution time binding or run time binding.

Message Passing : Message passing is a type of communication between processes. Message


passing is a form of communication used in parallel programming and object-oriented
programming.

Inheritance: It is defined as acquiring the properties from base class to derived class. By these
we can achieve code reusability .The base class can be called as parent class and derived class
can be called as child class. In this figure Class Rose acquires the properties of Flower data
member that is color.
5

Abstraction: Abstraction is defined as hiding the back ground details to the outside world. Only
the functionality will be provided to user. Let us consider an real time example of ATM machine
the use inserts the card and enter the pin for transition and does the transition but he doesn’t
know the working mechanism used internally for reading the card and how the card has been
connect the his account number. In object oriented programming we can abstract data and
process.

Encapsulation: Combining of data members and member functions into single unit is called
encapsulation.  Encapsulation also hides the data to other class. Consider a real time example of
encapsulation; in a company there are different sections like the accounts section, finance
section, sales section etc. The finance section handles all the financial transactions and keeps
records of all the data related to finance. Similarly the sales sections handle all the sales related
activities and keep records of all the sales. Now there may arise a situation when for some
reason an official from finance section needs all the data about sales in a particular month. In
this case, he is not allowed to directly access the data of sales section. He will first have to
contact some other officer in the sales section and then request him to give the particular data.
This is what encapsulation is. Here the data of sales section and the employees that can
manipulate them are wrapped under a single name “sales section”.

Polymorphism: It is a Greek word which is Ploy means many forms . It is defined as one
method can be implemented in many forms which means one method can perform different
tasks. Lets us take an example of a car. A car has a gear transmission system. It has four front
gears and one backward gear. When the engine is accelerated then depending upon which gear
is engaged different amount power and movement is delivered to the car. The action is same
applying gear but based on the type of gear. Polymorphism can be achieved statically and
dynamically

Advantages of OOPs: Code Reuse and Recycling, Encapsulation, Design Benefits, Software
Maintenance.
6

Q2. Procedural Programming Language and Object Oriented Language,

Object oriented language: Procedural programming language


OOP takes a bottom-up approach in POP follows a top-down approach.
designing a program.

Program is divided into objects depending Program is divided into small chunks based on
on the problem. the functions.

Each object controls its own data. Each function contains different data.
Focuses on security of the data Follows a systematic approach to solve the
irrespective of the algorithm. problem.

The main priority is data rather than Functions are more important than data in a
function in a program. program

The functions of the objects are linked via Different parts of a program are
message passing. interconnected via parameter passing.

Data hiding is possible in OOP. No easy way for data hiding.


Inheritance is allowed in OOP. No such concept of inheritance in POP.
Operator overloading is allowed. Operator overloading is not allowed
C++, Java.
Pascal, Fortran.

Q3. Applications of OOP

There are mainly 4 type of applications that can be created using java programming:
Standalone Application, Web Application, Enterprise Application, Mobile Application.

Q4. History and features of Java


7

Java is inherited form 2 languages that are C and C++.It is pure Object oriented
language.. Sun Microsystems initiated to develop a language for digital devices. It was invented
by James Gosling in June 1991.The language was initially called Oak. Later the project renamed
Java.

Java features :

JAVA is Object-Oriented while C is procedural.


Java is an Interpreted language while C is a compiled language.
C is a low-level language while JAVA is a high-level language.
C uses the top-down approach while JAVA uses the bottom-up approach.

Simple: Java is simple language to learn because all syntaxes are based on C and C++.

Object-Oriented: Java is an object-oriented programming language. Everything in Java is an


object.

Platform independent : The languages like c and C++ are platform dependent means which
depends on particular operating system. Java is platform independent which means compiled
into platform specific machines while Java is a write once, run anywhere language.

Secured : Java is best known for its security. With Java, we can develop virus-free systems.
Java is secured because No explicit pointer, Java Programs run inside a virtual machine .

Robust : Robust means strong. Java is robust because it uses strong memory management.
There is a lack of pointers that avoids security problems. There is automatic garbage collection
in java .

Architecture-neutral : The Java designers made several hard decisions in the Java language and
the Java Virtual Machine in an attempt to alter this situation. Their goal was “write once; run
anywhere, anytime , forever.” To a great extent, this goal was accomplished.

Portable : Java is portable because it facilitates you to carry the Java byte code to any platform.
It doesn't require any implementation.

High-performance : Java is faster than other traditional interpreted programming languages


because Java byte code is "close" to native code. It is still a little bit slower than a compiled
language (e.g., C++). Java is an interpreted language that is why it is slower than compiled
languages, e.g., C, C++, etc

Distributed : Java is distributed because it facilitates users to create distributed applications in


Java. We can write programs which capture information and distributed it to clients. This is
possible because java can handle TCP/IP protocols.
8

Multi-threaded : Java supports Multi-threading . A thread is like a separate program,


executing concurrently. We can write Java programs that deal with many tasks at once by
defining multiple threads. The main advantage of multi-threading is that it doesn't occupy
memory for each thread. It shares a common memory area. Threads are important for multi-
media, Web applications, etc.

Dynamic : Java is a dynamic language. It supports dynamic loading of classes. It means classes
are loaded on demand. It also supports functions from its native languages, i.e., C and C++.

Scalability : Java platform can be implemented on wide range of computers with varying
levels of resources. This is possible because java is compact and platform independent.

Q5. Java Virtual Machine (JVM),

Java virtual Machine is the heart of entire java program execution process. It takes the .Class
file as input and converts the byte code into machine language that is executed by processor.
9

Class Loader : Java file written by the programmer will be compiles by java compiler that
generates Class file called as byte code this class file will be given to class loader .It loads .class
file into memory.

The JVM memory has been divided into:

Method Area: Method area stores code of variables and code in the methods (functions)

Heap: objects will create in heap memory. Whenever JVM loads a class, a method and heap
area is immediately created in it.

Java Stacks: Method area is used to store methods. If java program requires more memory to
store data and results then java stacks are used.

PC(Program counter) registers: Program Counter is a register which stores the address the
method Instruction to be executed.

Native Method stacks: Native methods such as C and C++ functions will be executed in native
method stack .To execute native methods it requires native method library these are connected
to JVM by native method interface.

Execution Engine contains interpreter and JIT(Just It Tie ) compiler which are responsible for
converting byte code to machine instructions .JVM uses both interpreter and compiler .This
technique is called adaptive optimizer.

Q6. Java Program Structure

As java is pure object oriented language everything in java program should place in class even
main should be placed in a class.

sample program

class Example
{
public static void main(String args[])
{
System.out.println("Hello World");
}}

C:/>javac Example.java C:/> java Example

Output: Hello World


10

1. comments

While writing a program it is important it should be readable and understandable for this
purpose we use comments .When we write a comment in a program we can understand what
the is program is doing and users can understand the code. There are 3 types of comments

1) Single line comments: it has single line as comment. It is represented as //


For example
//This is a java single line comment
2) Multi line comment: If we want to write multiple lines of description then we can use
multi line comment it starts with /* and ends with */ for example

/* This is java multi line comment.

Which can have multiple lines? */

3) Java documentation comments: these are used for giving description for every feature
in a java program. This description proves helpful in creation of .html file called API It
starts wit /** and ends with */ for example
/** description about a class */
Code
/** description about method */

Q7. Reserver Wods /Keywords

Q8. Modifiers(Access Specifies)


11

An access specifier is a key word that tells us how to access the members of a class .We can use
access specifiers before a class and its members. There are four access specifiers available in
Java:

private: 'private' members of a class are not accessible anywhere outside the class. They are
accessible only within the class by the methods of that class. In this example the program
variable a , msg() method is of private type so they can’t be accessed outside the class.

class A{   public class Simple{  
private int a=40;    public static void main(String args[]){  
private void msg()   A obj=new A();  
{   System.out.println(obj.a);//Compile Time Error
System.out.println("Hello java"); obj.msg();//Compile Time Error  
}      }  
}   }  

public: 'public' members of a class are accessible everywhere. Outside the class. So any other
program can read them and use them.
class A{   public class Simple{  
public int a=40;    public static void main(String args[]){  
public void msg()   A obj=new A();  
{  System.out.println(obj.a);
System.out.println("Hello java"); obj.msg();
}}    } } 

Protected: The protected access modifier is accessible within package and outside the package
but through inheritance only. The protected access modifier can be applied on the data
member, method and constructor. It can't be applied on the class.

class A{   public class Simple{  
 protected int a=40;    public static void main(String args[]){  
 protected void msg()   A obj=new A();  
{    System.out.println(obj.a);//Compile Time Erro
System.out.println("Hello java" r  
); obj.msg();//Compile Time Error  
}}    }  }  
12

default: If no access specifier is given, then the Java compiler uses a 'default' access specifier.
'default' members are accessible outside the class, but within the same directory. ·

class A{   public class Simple{  
int a=40;    public static void main(String args[]){  
void msg()   A obj=new A();  
{    System.out.println(obj.a);
System.out.println("Hello java"); obj.msg();
}      }  
}   }  

  
Q9. Statements & Control Flow Statement

A statement specifies an action in a Java program, such as assigning the sum of x and y to z,
printing a message to the standard output, writing data to a file, etc.

Statements in Java can be broadly classified into three categories:

 Declaration statement
 Expression statement
 Control flow statement

Declaration Statement : A declaration statement is used to declare a variable.


For example int num; int num2 = 100; String str;

Expression Statement : An expression with a semicolon at the end is called an expression


statement. For example,

/Increment and decrement expressions

num++; ++num; num--; --num;

 //Assignment expressions

num = 100; num *= 10;

 //Method invocation expressions


13

System.out.println("This is a statement");

someMethod(param1, param2);

Control Flow Statement

By default, all statements in a Java program are executed in the order they appear in the
program. Sometimes you may want to execute a set of statements repeatedly for a number of
times or as long as a particular condition is true.

Q10. Primitive data types

In Java we have eight primitive types of data: byte, short, int, long, char, float, double, and
boolean. The primitive types are also commonly referred to as simple types; these can be put in
four groups:
• Integers: It has byte, short, int, and long, which are for whole-valued signed numbers.
• Floating-point: It has float and double, which represent numbers with fractional precision.
• Characters this has char, which represents symbols in a character set
• Boolean: It is a special type for representing true/false values.

Integer types:
Numbers without fractional parts and decimal parts is called integers

Data Type Size range


byte 1 bytes 128 to +127
Long 8 bytes -9223372036854775808
to
+9223372036854775807
Int 4 bytes -2147483648 to
+2147483647
short 2 bytes -32768 to +32767

For example long is a signed 64-bit type and is useful for those occasions where an int type is
not large enough to hold the desired value. The range of a long is quite large. This makes it
useful when big, whole numbers are needed.
14

Floating-Point Types : Floating-point numbers, also known as real numbers, are used when
evaluating expressions that require fractional precision

Data Type Size range


Float 4 bytes 1.4e–045 to 3.4e+038
Double 8 bytes 4.9e–324 to 1.8e+308

difference between float and double : Float can represent up to 7 digits accurately after
decimal point, whereas double can represent up to 15 digits accurately after decimal point.

float a=5.7F

the variable ‘a’ is having a value 5.7 F if F is not written at the end, by default JVM would have
taken it as double and allocates 8 bytes by placing F or f at the end of a value we can ask the
JVM to consider it as a float value and allocates only 4 bytes.

Characters
This data type represents a single character
Data Type Size range
Char 2 bytes 0 to 65536

Characters are represented as char in java. In C/C++ char is 8 bits wide. This is not the case in
Java. Java uses Unicode to represent characters. Unicode defines a fully international character
set that can represent all of the characters found in all human languages. It is a unification of
dozens of character sets, such as Latin, Greek, Arabic, Cyrillic, Hebrew, Katakana, Hangul, and
many more. For this purpose, it requires 16 bits.

Booleans : Java has a primitive type, called boolean, which have two values either true or false
This is the type returned by all relational operators, as in the case of a < b. boolean is also the
type required by the conditional expressions that govern the control statements such as if and
for. True or false are represented as 0(false) or 1(true)

Q11. Scope and Life time of Variable

The Scope and Lifetime of Variables : The scope of a variable is defined as within the block or
outside the block. Block starts with an opening curly brace and ended by a closing curly brace. 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. Lifetime of a variable
is defined as how long the variable exists before it is destroyed. Destroying variables refers to
15

de-allocating the memory that was allotted to the variables it was declared It also determines
the lifetime of those objects.

Languages like C and C++ defines the scope in two ways i.e. local and global variables .local
variables are the variables that are defined inside main() method global variables are that are
defined outside the main() method. However in java two major scopes that are those defined
by a class and those defined by a method.

//example on scope of a variable


class ScopDemo
{
public static void main(String args[])
{
int a; // visible to complete main block
a = 1;
if(a >=0)
{
// begun a new scope
int b = 4; // visible only to this block
// a and b are visible here
System.out.println(“a and b: " + a + " " + b);
}
System.out.println( “b:”+b) //This statement raises an Error as b not
known here
// a is still known here.
System.out.println("a is " + a);
}
}

Q12. Variable Type

Java Variable Types : Java has different of variables different types depending upon they
declared.

Local Variables : The scope of local variable is within the block or a method body are a
constructor Local variables are created when control enters into the block or
constructor of method's body and are destroyed once the control exits from the block.
Local variables are only visible to blocks where they are declared; they are not
accessible to outside block.
16

Instance Variables or Non-Static Fields : Variables that are non-static and declared out the block
or a constructor or a method is called instance variable. Instance variables are created when an
object of a class is created by using new keyword. Objects store their states in non-static
instance variables.

Class Variables or Static Fields : Class variables in Java are fields declared with static keyword.
Modifier static informs the compiler that there will be only one copy of such variables created
regardless of how many objects of this class are created. Static variables are created when a
class is loaded into the memory by the class loader and destroyed when a class is destroyed or
unloaded. Visibility of static fields will depend upon access modifiers. Default vales given to the
static members will follow the same rule as it is done in instance variables.

Q13. Main function

The main() method : If main method is not written in a java program JVM will not execute
it, main () is the starting point for JVM to start execution of a java program. Next to class is

public static void main (String args[]) :

JVM is the program written by java soft people and main () is written by us. Since main ()
method should be available to JVM, it should be declared as public. As main () is a method and
a method is executed by calling a method.

call a method : Create a object to class to which the method belongs to. The syntax of
creating the object is:

Classname objectname=new classname();

Then the method is called as objectname.method();

We call main () method without creating an object .such methods are called static
methods and should be declared as static. If a method is not returning any value then
should be defined as void before method name .void means no value i.e. main ()
method returns nothing. main () method is followed by String args[] main () method also
accepts some data from us. For example, it accepts group of strings, which is also called
as sting type array.

public static void main (string args[])


17

args[] is a array of string type it stores group of stings ,it also stores numbers but
stores it in the form of string only. The values passed to main are called as arguments
these arguments are stored in args[].

What happens if Sting args[] is not written in main() method : When main () method is
written without String args[] as Public static void main ().The code will compile but JVM
cannot run the code because it cannot recognize the main () method as the method
from where it should start execution of java program.JVM looks for main () method with
string type as parameter.

Q14. Include Vs Import

If we write a C or C++ program initially we include the header files by using


#include<stdio.h>.This means a request to C/C++ compiler to include the header file

header file : A header file is the file which contains functions code of function in a
program. For example <stdio.h> contains functions like printf(),sacnf() etc., so if we what to
use this functions we have include<stdio.h>. But in java to include a header file by using
import statement.

Example:
Import java.lang.system;

Difference between import and include:

When we use include statement the compiler goes to library and searches for that particular
header file .if it was found it copies the content of header file into program where the # include
is statement is written. Thus if program has 3lines and header file has 100 lines finally it has
103 lines which occupies the program memory which is wasted and processor tie is wasted. But
in java we use import statement instead of include by using import Java JVM go to library
execute the code there and substitute the result into program .so the addition storage for
header file saved and processor time is not wasted.

The import statement is used to import classes or interfaces in packages. A package is a kind of
directory that contains group of classes and interfaces. Java has several such packages in its
library.
18

Java library
|
Packages
|
Class’s |interfaces
|
Methods

 The first statement should be import i.e


Import java.lang.System;
That means System is class which is present in language (lang ) sub package that lang
sub package is located in the root package called java. In the above statement the
import statement imports only system class in lang package if we want to import all the
classes and interfaces in a package we use ‘ *’ i.e
Import java.lang.* //* indicates all the classes and interfaces

Q15. Identifiers and Literals

Identifiers: Identifiers are used for class names, method names, and variable names. An
identifier may be 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.

Literals : A literal represents a value that is stored into a variable directly in the program.
Ex : boolean a= true ; short s = 1;

Integer literals
Float literals
Character literals
String literals
Boolean literals
19

Q16. Operators

Operator is a symbol which performs operations, operator has to be placed between operands .i.e.

There are three types of operators Unary, Binary and Ternary Operator.

Unary : In Java, unary arithmetic operators are used to increasing or decreasing the value of an
operand. Increment operator adds 1 to the value of a variable, whereas the decrement operator
decreases a value. Increment and decrement unary operator works as follows:
Syntax:
val++;
val--;
These two operators have two forms: Postfix and Prefix. Both do increment or decrement in
appropriate variables. These two operators can be placed before or after of variables. When it is
placed before the variable, it is called prefix. And when it is placed after, it is called postfix.
Following example table, demonstrates the work of Increment and decrement operators with
postfix and prefix:
Example Description
val = a++; Store the value of "a" in "val" then increments.
val = a--; Store the value of "a" in "val" then decrements.
val = ++a; Increments "a" then store the new value of "a" in "val".
val = --a; Decrements "a" then store the new value of "a" in "val".

Ternary operators: ternary operator is also known as the conditional operator. This operator
consists of three operands and is used to evaluate Boolean expressions. The goal of the operator
is to decide, which value should be assigned to the variable. The operator is written as −
variable x = (expression) ? value if true: value if false

Arithmetic Operators +,-,*,/,%,++,--


Assignment Operators =,+=,-=,*=,/=,%=,&=,|=,^=,>>=,<<=
Comparission Operators ==,!=,>,<,>=,>=
Logical operators &&,||,!
Others , new
20

Bitwise Operators :

Bitwise OR (|) : This operator is binary operator, denoted by ‘|’. It returns bit by bit OR of input
values, i.e, if either of the bits is 1, it gives 1, else it gives 0.
For example,
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)

Bitwise OR Operation of 5 and 7


0101
| 0111
________
0111 = 7 (In decimal)

Bitwise AND (&) :This operator is binary operator, denoted by ‘&’. It returns bit by bit AND of
input values, i.e, if both bits are 1, it gives 1, else it gives 0.
For example,
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)

Bitwise AND Operation of 5 and 7


0101
& 0111
________
0101 = 5 (In decimal)

Bitwise XOR (^) : This operator is binary operator, denoted by ‘^’. It returns bit by bit XOR of
input values, i.e, if corresponding bits are different, it gives 1, else it gives 0.
For example,
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)

Bitwise XOR Operation of 5 and 7


0101
^ 0111
________
0010 = 2 (In decimal)

Bitwise Complement (~) :This operator is unary operator, denoted by ‘~’. It returns the one’s
compliment representation of the input value, i.e, with all bits inversed, means it makes every 0
to 1, and every 1 to 0.
For example,
a = 5 = 0101 (In Binary)

Bitwise Compliment Operation of 5


21

~ 0101
________
1010 = 10 (In decimal)
Note – Compiler will give 2’s complement of that number, i.e., 2’s compliment of 10 will be -6.

// Java program to illustrate // bitwise or


// bitwise operators // 0101 | 0111=0111 = 7
public class operators { System.out.println("a|b = " + (a | b));
public static void main(String[] args)
{ // bitwise xor
//Initial values // 0101 ^ 0111=0010 = 2
int a = 5; System.out.println("a^b = " + (a ^ b));
int b = 7;
// bitwise and
// bitwise and // ~0101=1010
// 0101 & 0111=0101 = 5 // will give 2's complement of 1010 = -6
System.out.println("a&b = " + (a & b)); System.out.println("~a = " + ~a);

// can also be combined with


// assignment operator to provide
shorthand
// assignment
// a=a&b
a &= b;
System.out.println("a= " + a);
}
}

Output :

a&b = 5
a|b = 7
a^b = 2
~a = -6
a= 5

Shift Operators: These operators are used to shift the bits of a number left or right thereby
multiplying or dividing the number by two respectively.

Signed Right shift operator (>>) :Shifts the bits of the number to the right and fills 0 on voids
left as a result. The leftmost bit depends on the sign of initial number. Similar effect as of
dividing the number with some power of two.
22

For example,
Example 1:
a = 10
a>>1 = 5

Example 2:
a = -10
a>>1 = -5

Unsigned Right shift operator (>>>) : Shifts the bits of the number to the right and fills 0 on
voids left as a result. The leftmost bit is set to 0. (>>>) is unsigned-shift; it’ll insert 0. (>>) is
signed, and will extend the sign bit.
For example,
Example 1:
a = 10
a>>>1 = 5

Example 2:
a = -10
a>>>1 = 2147483643
DOES NOT preserve the sign bit.

Left shift operator (<<) : Shifts the bits of the number to the left and fills 0 on voids left as a
result. Similar effect as of multiplying the number with some power of two.
For example,
a = 5 = 0000 0101
b = -10 = 1111 0110

a << 1 = 0000 1010 = 10


a << 2 = 0001 0100 = 20

b << 1 = 0000 1010 = -20


b << 2 = 0001 0100 = -40
23

Unsigned Left shift operator (<<<) : Unlike unsigned Right Shift, there is no “<<<" operator
in Java, because the logical (<<) and arithmetic left-shift (<<<) operations are identical.

// Java program to illustrate


// shift operators
public class operators {
public static void main(String[] args)
{

int a = 5;
int b = -10;

// left shift operator


// 0000 0101<<2 =0001 0100(20)
// similar to 5*(2^2)
System.out.println("a<<2 = " + (a << 2));
// right shift operator
// 0000 0101 >> 2 =0000 0001(1)
// similar to 5/(2^2)
System.out.println("b>>2 = " + (b >> 2));

// unsigned right shift operator


System.out.println("b>>>2 = " + (b >>>
2));
}
}
Output :

a<<2 = 20
b>>2 = -3
b>>>2 = 1073741821
24

Q17. Operator Precedence

The order of precedence for Java operators, from highest to lowest. operators: parentheses,
square brackets, and the dot operator. Technically, these are called separators.

Q18. Primitive type conversion and casting:

One type of value is assigned to another type. If the two types are compatible, then Java will
perform the conversion automatically (this is also called as implicit type conversion) . Using cast
operator which performs explicit conversion.

int a; //needs 32 bits

byte b=45; //needs the 8 bits

a=b; // here 8 bits data is placed in 32 bit storage. Thus widening takes place.

//automatic type conversion

long l = i;

//automatic type conversion

float f = l;
25

Casting Incompatible Types

Destination-variable= (target-datatype) value Here, target-datatype specifies the desired type


to convert the specified value to. For example,

int a=1234;

byte b=(byte) a;

int a=258;

byte b;

b=(byte) a;

Q19. Control Statements

i. Selection statements
ii. Iteration statements
iii. Jump statements

Q20. Method Overloading

In Java it is possible to define two or more methods within the same class that share the same
name, as long as their parameter declarations are different. When this is the case, the methods
are said to be overloaded, and the process is referred to as method overloading. Method
overloading is one of the ways that Java supports polymorphism.When an overloaded method
is invoked,

You might also like