Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
5 views34 pages

Unit 1 Fundamental

The document provides an overview of Java's history, development, and core principles, emphasizing its evolution from a language designed for consumer electronics to one focused on internet programming. It details key concepts of Object-Oriented Programming (OOP) such as abstraction, encapsulation, inheritance, polymorphism, and reusability, which are foundational to Java. Additionally, it covers the Java Development Kit (JDK), data types, and examples of Java programming, including arrays and strings.

Uploaded by

nirajant1
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)
5 views34 pages

Unit 1 Fundamental

The document provides an overview of Java's history, development, and core principles, emphasizing its evolution from a language designed for consumer electronics to one focused on internet programming. It details key concepts of Object-Oriented Programming (OOP) such as abstraction, encapsulation, inheritance, polymorphism, and reusability, which are foundational to Java. Additionally, it covers the Java Development Kit (JDK), data types, and examples of Java programming, including arrays and strings.

Uploaded by

nirajant1
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/ 34

Java unit -1 Fundamental

1.1 history of java


2 History and Development of java:- java is related to C++, which is a direct descendent
of C. much of the character of java is inherited from these two languages. C, java derives
its syntax. Many of java’s object-oriented features were influenced by C++.

The c language shook the computer world. Its impact should not be underestimated,
because it fundamentally changed the way programming was approached and thought
about . the creation of C was a direct result of the need for a structured, efficient, high-
level language that could replace assembly code when creating systems program.
Java’s core principles developed out of a desire to build software for consumer
electronics. It all started out in 1990 when a team of Sun researchers developed some
concepts for a new direction in high-tech, consumer-driven technology. Computers were
everywhere and were the driving force behind many of the products in the home: the
VCR, the microwave oven, the security system, and the stereo system.

Java was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank and
Mike Sheridan at Sun Microsystems, Inc. in 1991, ti took 18 months to develop the first
working version. This language was initially called “Oak” but was renamed “java” in
1995. between the initial implementation of Oak in the fall of 1992 and the public
announcement of java in the spring of 1995, many more people contributed to the design
and evolution of the language. Bill Joy, Arthur van Hoff, Jonathan Payne, Frank Yelling,
and Tim Lindholm were key contributors to the maturing of the original prototype.

By 1993, it became obvious to members of the java design team that the problems of
portability frequently encountered when creating, code for embedded controllers are also
found when attempting to create code for the internet. In fact, the same problem that Java
was initially designed to solve on a small scale could also be applied to the internet on a
large scale. This realization caused the focus of java to switch from consumer electronic
to internet programming . so, while the desire for an architecture –neutral programming
language provided the initial spark, the internet ultimately let to java’s large scale success.

The initial release of java was nothing short of revolutionary, nut is did not mark the end
of java’s era of rapid innovation. Unlike most other software systems that usually settle
into a pattern of small, incremental improvements, java continued to evolve at an
explosive pace. Soon after the release of java 1.0, designers of java had already created
java 1.1. the features added by java 1.1 were more significant and substantial than the
increase in the minor revision.

1.2 Object Oriented Programming

1.1 object oriented programming is at the core of java. In fact, all java programs are object-
oriented.
There are following characteristic of object oriented programs.
1. Abstraction: an essential element of object-oriented programming is abstraction.
Humans manage complexity through abstraction. For example, people do not think of a
car as a set of tens of thousands of individual parts. They think if it as a well-defined
object with is own unique behavior. This abstraction allows people to use a car to drive
to the grocery store without being overwhelmed by the complexity of the parts that form
the car. They can ignore the details of how the engine, transmission, and braking systems
work. Instead they are free to utilize the object as a whole. A powerful way to manage
abstraction is through the use of hierarchical classifications. This allows we to layer the
semantics of complex systems, breaking them into more manageable pieces.
2. Encapsulation: encapsulation is the mechanism that binds together code and the data it
manipulates, and keeps both safe from outside interference and misuse. One way to think
about encapsulation is as a protective wrapper that prevents the code and data from being
arbitrarily accessed by other code defined outside the wrapper. Access to the code and
data inside the wrapper is tightly controlled through a well-defined interface. To relate
this to the real world.
3. inheritance:- inheritance is the process by which one object acquires the properties of
another object. This is important because it supports the concept of hierarchical
classification. For example, a Golden Retrieve is part of the classification dog, which in
turn is part of the mammal class, which in under the larger class animal. Without the use
of hierarchies, each object would need to define all of its characteristics explicitly. It can
inherit its general attributes from its parent. Thus, it is the inheritance mechanism that
makes it possible for one object to be a specific instance of a more general case.
4. polymorphism :- polymorphism is a feature that allows one interface to be used for a
general class of actions. The specific action is determined by the exact nature of the
situation. More generally, the concept of polymorphism is often expressed by the phrase
“one interface, multiple methods”. This means that it is possible to design a generic
interface to a group of related activities. This helps reduce complexity by allowing the
same interface to be used to specify a general class of action.

5. Classes :- the entire set of data and code on an object can be made a user define data type
with help of class. In fact , objects are variables of the type class. Once a class has been
defined, we can create any number of object. Generally, class contains the set of same
type of objects. In other words, class is user define data type that is use to bind the data
members and function together.
6. Reusability :- it is an striking feature of OOP language. The reusability means, to use
many times , the pre-existing program, or component, class without modifying and
writing code again and again. By this way, the programmer can save a lots of time ,
program can be easily developed, and we have use our less effort and program will be
ready.
When program developed in short time , it means , we save the money too. With saving
our efforts, we save the compilation and debugging time too. The reusability can be
achieved by using inheritance. In inheritance, we derive a new class from pre-existing
class, and add new program and component. By this way , we developed the pre-existing
classes.
7. Object :- object is an instance of a class. When a class is defined, it means we have
define a template. After define a class, now we can create any number of objects. And by
using the object, can access the member of a class outside of class.
1.3.1 java development kit
2 Java SE 17 Archive Downloads
3 Go to the Oracle Java Archive page.
4 The JDK is a development environment for building applications using the Java
programming language.
5 The JDK includes tools useful for developing and testing programs written in the Java
programming language and running on the JavaTM platform.
6 WARNING: These older versions of the JDK are provided to help developers debug
issues in older systems. They are not updated with the latest security patches and are
not recommended for use in production.
7 For production use Oracle recommends downloading the latest JDK version.
8 Only developers and enterprise administrators should download these releases.
9 For current Java releases, please visit Oracle Java SE Downloads.
10 Java SE Development Kit 17.0.8
11 This software is licensed under the Oracle No-Fee Terms and Conditions License.

12

12.3 First java simple program

Import java.lang.*;
public class demo
{
public static void main(String args[])
{
System.out.println(“Hello Students”);
}
}

Skilton of java program


Import packages
Public class className
{
Variable declarations
Int a,b,c;
Method declaration
Public void display()
{
Statements;
}
Public static void main(String args[])
{
//Creating class object
ClassName obj=new className();
//calling methods
Obj.display();
}
}

12.4 packages in java

A java package is a group of similar types of classes, interfaces and sub-packages.

Package in java can be categorized in two form, built-in package and user-defined package.

There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.

Here, we will have the detailed learning of creating and using user-defined packages.
12.5 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.

Primitive data types


Java defines 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, and both terms will be
used in this book. These can be put in four groups:
1. Integer Data type:- java defines four integer types : byte, short, int and long. Java
does not support unsigned, positive-only integers.

Name Width Range


Long 64 bits -9223372036854808 - 9223372036854808
int 32 -2147483648 to 2147483648
short 16 -32768 to 32 767
byte 8 -128 to 127
byte – the smallest integer byte is byte. This is a signed 8-bit type that has a range from
-128 to 127.
Short- short is a singed 2 bytes type. It has range from -32768 to 32 767. this tpe is mostly
applicable to 16 bit computers.
Int – the most commonly used integer type is int. it is a singed 4 bytes tpe that has a range
from -2147483648 to 2147483648
Long- long is a signed 64-bit type and is useful for those occasions where an int type is not
large enough to hold the desire value.

2. Floating point types: floating point numbers, also known as real numbers, are used
when evaluating expressions that require fractional precision.

A. float : the type float specifies a single-precision value uses 32 bits of storage.
Single precision is faster on some processors and takes half as much space as
double precision, but will become imprecise when the values are either very
large or very small. It has 32 bits space range from 3.4e-38 to 3.4e+38.
B. Double precision, as denoted by the double keyword, uses 64 bits to store a
value. Double precision is actually faster than single precision on some modern
processor that have been optimized for high-speed mathematical calculations.
It’s range from 1.7e-308 to 1.7e+308.

2. Characters :- in java, the data type used to store characters in char. However, c/c++
programmers beware: char in java is not the same as char in c or c++, char is
an integer type that is 8byte wide. This is not case in java. Instead, java uses
Unicode to represent characters. Unicode defines a fully international character
set that can represent characters all of the characters sets, such as Latin, Greek
etc.
3. Booleans :- java has a simple type called Boolean, for logical values. It can have only
one of two possible values, true or false. This is type returned by all relational
operators.

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

Example:

1. Boolean one = false

Example:

1. byte a = 10, byte b = -20

Example:

1. short s = 10000, short r = -5000

Example:

1. int a = 100000, int b = -200000

Example:

1. long a = 100000L, long b = -200000L

Example:

1. float f1 = 234.5f

Example:

1. double d1 = 12.3
Java Strings

Strings are used for storing text.

A String variable contains a collection of characters surrounded by double quotes:

Example
Create a variable of type String and assign it a value:

String greeting = "Hello";

Example

String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

System.out.println("The length of the txt string is: " + txt.length());

String txt = "Hello World";

System.out.println(txt.toUpperCase()); // Outputs "HELLO WORLD"

System.out.println(txt.toLowerCase());

Arrays
An array is a group of like-typed variables that are referred to by a common name. Arrays of
any type can be created and may have one or more dimensions. A specific element in an array.
One-Dimensional Arrays
A one-dimensional array is, essentially, a list of like-typed variables. To create an array, you
first
must create an array variable of the desired type. The general form of a one-dimensional
array declaration is

type var-name[ ];

Here, type declares the base type of the array. The base type determines the data type of each
element that comprises the array. Thus, the base type for the array determines what type of
data the array will hold. For example, the following declares an array named month_days
with the type “array of int”:

int month_days[];

Although this declaration establishes the fact that month_days is an array variable, no
array actually exists. In fact, the value of month_days is set to null, which represents an array
with no value. To link month_days with an actual, physical array of integers, you must allocate
one using new and assign it to month_days. new is a special operator that allocates memory.
You will look more closely at new in a later chapter, but you need to use it now to allocate
memory for arrays. The general form of new as it applies to one-dimensional arrays appears
as follows:

array-var = new type[size];

Here, type specifies the type of data being allocated, size specifies the number of elements in
the array, and array-var is the array variable that is linked to the array. That is, to use new to
allocate an array, you must specify the type and number of elements to allocate. The elements
in the array allocated by new will automatically be initialized to zero. This example allocates
a 12-element array of integers and links them to month_days.

month_days = new int[12];


class Array {
public static void main(String args[]) {
int month_days[];
month_days = new int[12];
month_days[0] = 31;
month_days[1] = 28;
month_days[2] = 31;
month_days[3] = 30;
month_days[4] = 31;
month_days[5] = 30;
month_days[6] = 31;
month_days[7] = 31;
month_days[8] = 30;
month_days[9] = 31;
month_days[10] = 30;
month_days[11] = 31;
System.out.println("April has " + month_days[3] + " days.");
}}
// An improved version of the previous program.
class AutoArray {

public static void main(String args[]) {

int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31,30, 31 };

System.out.println("April has " + month_days[3] + " days.");


}
}
Here is one more example that uses a one-dimensional array. It finds the average of a set
of numbers.
// Average an array of values.
class Average {
public static void main(String args[])
{
double nums[] = {10.1, 11.2, 12.3, 13.4, 14.5};
double result = 0;
int i;
for(i=0; i<5; i++)
result = result + nums[i];
System.out.println("Average is " + result / 5);
}
}
Multidimensional Arrays
In Java, multidimensional arrays are actually arrays of arrays. These, as you might expect, look
and act like regular multidimensional arrays. However, as you will see, there are a couple
of subtle differences. To declare a multidimensional array variable, specify each additional
index using another set of square brackets. For example, the following declares a two
dimensional
array variable called twoD.

int twoD[][] = new int[4][5];


// Demonstrate a two-dimensional array.
class TwoDArray {
public static void main(String args[]) {
int twoD[][]= new int[4][5];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<5; j++)
{
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++)
{
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}

// Manually allocate differing size second dimensions.


class TwoDAgain {
public static void main(String args[]) {
int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<i+1; j++)
{
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<i+1; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}

Alternative Array Declaration Syntax


There is a second form that may be used to declare an array:

type[ ] var-name;

Here, the square brackets follow the type specifier, and not the name of the array variable.
For example, the following two declarations are equivalent:

int al[] = new int[3];


int[] a2 = new int[3];

The following declarations are also equivalent:

char twod1[][] = new char[3][4];


char[][] twod2 = new char[3][4];

1.7 Closer Look at Literals


Integer Literals
Integers are probably the most commonly used type in the typical program. Any whole number
value is an integer literal. Examples are 1, 2, 3, and 42. These are all decimal values, meaning
they are describing a base 10 number. There are two other bases which can be used in integer
literals, octal (base eight) and hexadecimal (base 16). Octal values are denoted in Java by a
leading zero. Normal decimal numbers cannot have a leading zero. Thus, the seemingly valid
value 09 will produce an error from the compiler, since 9 is outside of octal’s 0 to 7 range.
Amore common base for numbers used by programmers is hexadecimal, which matches
cleanly with modulo 8 word sizes, such as 8, 16, 32, and 64 bits. You signify a hexadecimal
constant with a leading zero-x, (0x or 0X). The range of a hexadecimal digit is 0 to 15, so A
through F (or a through f ) are substituted for 10 through 15.

Floating-Point Literals
Floating-point numbers represent decimal values with a fractional component. They can be
expressed in either standard or scientific notation. Standard notation consists of a whole
number
component followed by a decimal point followed by a fractional component. For example, 2.0,
3.14159, and 0.6667 represent valid standard-notation floating-point numbers. Scientific
notation
uses a standard-notation, floating-point number plus a suffix that specifies a power of 10 by
which the number is to be multiplied. The exponent is indicated by an E or e followed by a
decimal number, which can be positive or negative. Examples include 6.022E23, 314159E–05,
and 2e+100.

Boolean Literals
Boolean literals are simple. There are only two logical values that a boolean value can have,
true and false. The values of true and false do not convert into any numerical representation.
The true literal in Java does not equal 1, nor does the false literal equal 0. In Java, they can
only
be assigned to variables declared as boolean, or used in expressions with Boolean operators.

Character Literals
Characters in Java are indices into the Unicode character set. They are 16-bit values that can
be converted into integers and manipulated with the integer operators, such as the addition
and subtraction operators. Aliteral character is represented inside a pair of single quotes. All
of the visible ASCII characters can be directly entered inside the quotes, such as ‘a’, ‘z’, and
‘@’.
For characters that are impossible to enter directly, there are several escape sequences that
allow
you to enter the character you need, such as ‘\’’ for the single-quote character itself and ‘\n’ for
the newline character. There is also a mechanism for directly entering the value of a character
in
octal or hexadecimal. For octal notation, use the backslash followed by the three-digit
number. For example, ‘\141’ is the letter ‘a’. For hexadecimal, you enter a backslash-u (\u),
then
exactly four hexadecimal digits. For example, ‘\u0061’ is the ISO-Latin-1 ‘a’ because the top
byte
is zero. ‘\ua432’ is a Japanese Katakana character. Table 3-1 shows the character escape
sequences.

String Literals
String literals in Java are specified like they are in most other languages—by enclosing
a sequence of characters between a pair of double quotes. Examples of string literals are
“Hello World”
“two\nlines”
“\”This is in quotes\”“
1.8 Variables :-the variable is the basic unit of storage in a java program. A variable is defined
by the combination of an identifier, a type and optional initialize. In addition, all variables have
a scope, which defines their visibility and a lifetime. These elements are examined next.

(i) Declaring Variables : in java, all variables must be declared before they can
be used. The basic form of a variable declaration is shown bellow.
Type identifier=[value],identifier =[value];
For example:
int a, b, c;
int x=3,y=33;
byte bt=44;
double pi=3.14159;
char tt=’c’;
(ii) Dynamic initialization :- although the preceding examples have used only
constants as initializes, java allows variables to be initialized dynamically, using any
expression valid at the time the variable is declared.

For example.

class simpleint
{
public static void main(String s[])
{
double p=800,t=2,r=7.5;
//si is dynamically initialized.
double si=(p*t*r)/100;
System.out.println(“simple interest is “+si);
}
}
(iii) The Scope and lifetime of variables:- So far, all of the variables used have been
decaled at the start of the main() method. However, java allows variables to be declared
within any block. A block defines a scope. Thus, each time we start a new block, we
are creating a new scope.
Most other computer languages defines two general categories of scopes: global and
local. However, these traditional scopes do not fit well with java’s strict, object-oriented
model. While it is possible to create what amounts to being a global scope is by far the
exception not the rule. In java, the two major scopes are those defined by a class and
those defined by a method.

For example.

Class Scope
{

public static void main(String args[])


{
int x;
x=100;
if(x==100)
{
int y=20;
System.out.println(“ x is “+x);
System.out.println(“ y is “+y);
}
// y=200 //error !! y not know here
// x is still known here.
System.out.println(“x is “+x);
}
}

Constant

As the name suggests, a constant is an entity in programming that is immutable. In other


words, the value that cannot be changed. In this section, we will learn about Java
constant and how to declare a constant in Java.

Static and Final Modifiers

o The purpose to use the static modifier is to manage the memory.


o It also allows the variable to be available without loading any instance of the class in
which it is defined.
o The final modifier represents that the value of the variable cannot be changed. It also
makes the primitive data type immutable or unchangeable.

The syntax to declare a constant is as follows

1. static final datatype identifier_name=value;

For example, price is a variable that we want to make constant.

1. static final double PRICE=432.78;

Where static and final are the non-access modifiers. The double is the data type and PRICE is
the identifier name in which the value 432.78 is assigned.

In the above statement, the static modifier causes the variable to be available without an
instance of its defining class being loaded and the final modifier makes the variable fixed.

Here a question arises that why we use both static and final modifiers to declare a constant?

If we declare a variable as static, all the objects of the class (in which constant is defined) will
be able to access the variable and can be changed its value. To overcome this problem, we use
the final modifier with a static modifier.

When the variable defined as final, the multiple instances of the same constant value will be
created for every different object which is not desirable.
1.9 Arithmetic Operator :- Arithmetic operators operate on arithmetic variable and
arithmetic literals. the arithmetic operators and the character symbol that represent them
are listed in the table

Operator symbols
Operation
Add +
Subtract -
Multiply *
Divide /
Modulus %

For example

public class math_test


{
public static void main(String args[])
{ int a,b,c,d;
a=10;
b=3;
c = a + b;
d= a % b;
System.out.println(“ Sum of two number is “+c);
System.out.println(“remainder is “+d);
}
Increment and Decrement Operators:

There are two more arithmetic operators ++ and --. Both are unary operators
and operate only on integers. The ++ increment operator increases the operand’s value by 1.
both can operate in prefix form ++N or postfix form N++, where N is a variable. In prefix
form, the value of the operand N is incremented first and the operand is used. The postfix form,
the value of the operand is used first and then incremented. The same is applicable to the
decrement operator --.

For example

Class intdrc
{
public static void main(String a[])
{
int m=25, p=70;
System.out.println(” m = “+ m);
System.out.println(” ++m = “ + ++m);
System.out.println(” p = “ + p);
System.out.println(” p++ = “ + p++);
}}

4.2 Bitwise Operator :

Bitwise Logical operators are used to manipulate individual bits of a data item.
There are situations where individual bits of a data are to be modified. Java provides a set of
bitwise operators. These operators opeate only on byte, short, int and long types.

a) Bitwise AND (&)


This AND operator, &, performs AND operation bit by bit operands.

00101010 42
& 00001111 15
-----------------
00001010 10

b) bitwise OR operator: the OR operator, 1, combines bits such that if


either of the bits in the operands is a 1, then the resultant bit is a 1, as
shown here.
00101010 42
| 00001111 15
-----------------
00101111 47

c) Bitwise NOT : also called the bitwise complement, the unary NOT
operator, ~, inverts all of the bits of its operand.

00101010 becomes 11010101


The left Shift Operator :- the left shift operator, << shifts all of the bits in a value to the
left a specified number of times. It has this general form;
Value<<num;

Here, num specifies the number of positions to left shift the value in value. That is, the <<
moves all of the bits in the specified value to the left by the number of bits positions specified
by num.
public class test
{
public static void main(String s[])
{
int a=7,b=0;
b= a<<2 ;
System.out.println("left shift is"+ b);
}
}
Right shift operator: the right shift operator,>> shifts all of the bits in a value toe right a
specified number of times. Its general form is shown here.
Value>>num;
Here, num specifies the number of positions to right-shift the value in order. That is
the >> moves all of the bits in the specified value to the right the number of
bit positions specified by num.
For example.

public class test


{
public static void main(String s[])
{

int a=32,b=0;
b= a>>2 ;

System.out.println("right shift is"+ b);


}
}
Relational Operators
The relational operators determine the relationship that one operand has to the other.
Specifically, they determine equality and ordering. The relational operators are shown here:

The outcome of these operations is a boolean value. The relational operators are most
frequently used in the expressions that control the if statement and the various loop statements.
Any type in Java, including integers, floating-point numbers, characters, and Booleans can be
compared using the equality test, ==, and the inequality test, !=. Notice that in Java equality is
denoted with two equal signs, not one. (Remember: a single equal sign is the assignment
operator.) Only numeric types can be compared using the ordering operators. That is, only
integer, floating-point, and character operands may be compared to see which is greater or less
than the other.

Boolean Logical Operators


The Boolean logical operators shown here operate only on boolean operands. All of the
binary logical operators combine two boolean values to form a resultant boolean value.
class BoolLogic {
public static void main(String args[]) {
boolean a = true;
boolean b = false;
boolean c = a | b;
boolean d = a & b;
boolean e = a ^ b;
boolean f = (!a & b) | (a & !b);
boolean g = !a;
System.out.println(" a = " + a);
System.out.println(" b = " + b);
System.out.println(" a|b = " + c);
System.out.println(" a&b = " + d);
System.out.println(" a^b = " + e);
System.out.println("!a&b|a&!b = " + f);
System.out.println(" !a = " + g);
}
}

The ? Operator
Java includes a special ternary (three-way) operator that can replace certain types of if-then-
else
statements. This operator is the ?. It can seem somewhat confusing at first, but the ? can be
used very effectively once mastered. The ? has this general form:

expression1 ? expression2 : expression3

Here, expression1 can be any expression that evaluates to a boolean value. If expression1 is
true, then expression2 is evaluated; otherwise, expression3 is evaluated. The result of the ?
operation is that of the expression evaluated. Both expression2 and expression3 are required
to return the same type, which can’t be void.
Here is an example of the way that the ? is employed:

ratio = denom == 0 ? 0 : num / denom;


Operator Precedence
Table shows the order of precedence for Java operators, from highest to lowest. Notice
that the first row shows items that you may not normally think of as operators: parentheses,
square brackets, and the dot operator. Technically, these are called separators, but they act
like operators in an expression. Parentheses are used to alter the precedence of an operation.

1.10 Type Conversion:- it is important to know beforehand what type an expression will give
when it is evaluated . it is necessary because an expression may contain different types. Java
has mechanism to handle different types present in an expression during evaluation or while
assignment. Java does the conversion through two mechanisms, automatic promotion and type
casting.

Automatic Promotion:- java automatically converts variables or literals of lower


precision type to a higher precision type during the evaluation of expression or during
assignment. This is know as automatic promotion. When unary operators like -,++ etc.
Operate on an operand of type byte or short, the operand will be converted to int type,
otherwise the operands are left as such. When binary operations take place, the type of
the operands are checked . if one of the operands is double, the other will be converted
to double. If one of the operands is float, the other will be converted to float and if one
of the operands is long, the other operand will be converted to long, otherwise the two
operands will be converted to int.
For example:
byte b1=35;
byte b2=++b1;
the second statement will give compile error because b1 is automatically promoted to
int.
byte b1=10,b2=20;
byte b3=b1+b2;
the second statement will give compile error as both b1 and b2 will be promoted to int
before the binary + is operated.

(ii) type casting (explicite) :- there are situations where incompatible type conversion
is needed, where a higher precision type is being assigned to or converted to a lower
precision. For example, it may be needed to get an int type or byte fro a float. This
processing is known as narrowing or down casting. The narrowing is to be done
explicitly by using the keyword type. The general form of type casting is

type variable = (type) expression;

e.g.
int p=20;
byte b=(byte)p;

if..else statement :- this statement helps to select one out of two possibilities based
on the given condition. Hence, this statement is also called as conditional if
statement.

The general form of this statement is:


If(conditional expression)
Statement1
Else
Statement2

The conditional expression should result in a Boolean value. If the condition,


on evaluation, gives true, statement1 is executed and the control skips statement2, otherwise
statement2 would be executed and statement1 is skipped.

public class selection1


{
public static void main(String s[])
{

int mark=50;
String result;
If(mark>=40)
Result=”pass”;
Else
Result=”fail”

System.out.println(“Result is “+result);
}
}

a) Nested if … else

Nested if..else statement is made by placing one if..else in another if..else statement.
Nested if..else statement helps to select one out of many choices. The general form
of if..else statement is :

If(condition1)
If(condition2)
If(condition1)
Statemebnt4
else
Statement3
else
Statement2
else
Statement1

class nestedif

{
public static void main(String s[])
{
String result;
Int avgmark=62;
If(avgmark> 50)
If(avgmark>=60)
If(avgmark>=75)
Result=”distinction”;
Else
Result=”first class”;
Else
Result=”second class”;
Else
Result=”third class”;

If(avgmark<50)
System.out.println(“failed”);
else
System.out.println(“passed with”+result); }
}

a) Ladder else if statement :- whenever, we have multiple choice and we have to


select one of them, in this case the ladder if can be used. The structure of this is as
follows.

If(condition1)
Statement1
Else if(condition2)
Statement2;
Else if(condition3)
Statement3;
Else
Statement4;
class ladderif
{
public static void main(String args[])
{
int mark=8;
String result;

If(mark>=75)
result=”Distiction”;
else if(mark>=60)
result=”first devision”;
else if(mark>=45)
result=”second devision”;
else if(mark>=35)
result=”third devision”;
else
Result=”failed”

System.out.println(“Result is ” +result);
} }

2. The switch Statement:- The switch helps to select one out of many choices. This helps to
write a clear statement when compared to nested if..else statement. The general form of switch
statement is

switch(expression)
{
case var1 : statement1;
break;
case var2 : statement2;
break;
case var3 : statement3;
break;
.
.
.
default : statement;
}

for example;

public class sitchdemo


{
public static void main(String args[])
{
int month=5;
switch(month)
{
case 1:
System.out.println(“January”);
break;
case 2:
System.out.println(“February”);
break;
case 3:
System.out.println(“March”);
break;
default:
System.out.println(“invalid month number”);
}
}
}

LOOPS

he Java 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.
There are three types of for loops in Java.

o Simple for Loop


o For-each or Enhanced for Loop
o While loop
o do-while loop

The while Statement:-

The while statement is used for looping or iterating a block of statements while given
condition it true. The general form of the while statement is

while(condition)
{
statements;
}

The condition, when evaluated must result in the Boolean value true or false.
As long as the condition gives true, the statement block will be executed . when the condition
becomes false, the control leaves the block statement. The flow of control in while statement
is given bellow

class whiledemo
{
public static void main(String args[])
{

int n=10;
int sum=0;
while(n>0)
{
sum = sum + n;
n--;
}
System.out.println(“sum of numbers form 1 to 10 is “+sum);
}
}

The do-while Statement:

This do..while control statement is used for looping a block of statements while
the given condition is true. In this structure, the condition is tested at the end of the block . this
is in contrast to the while.. statement, where the condition is tested at the start of the block. The
general form of do..while statement is .
do{
statements;
}while(condition);

Class dowhiledemp
{
public static void main(String args)
{
int n=10;
int sum;
do
{
sum=sum+n;
n--;
}while(n>0);
System.out.println(“sum of numbers from 1-10 is”+sum);
}
}

The for…. Statement


This is the third form of looping statement. This statement is a self, contained one that
is the initial value, termination condition, iterators are all given in the for structure itself. The
general form of for statement is:
for(initializer ; condition; iterator)
{
Statements ;
}

1. Initialization: It is the initial condition which is executed once when the loop starts.
Here, we can initialize the variable, or we can use an already initialized variable. It is
an optional condition.
2. 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. It must return boolean
value either true or false. It is an optional condition.
3. Increment/Decrement: It increments or decrements the variable value. It is an optional
condition.
4. Statement: The statement of the loop is executed each time until the second condition
is false.

For example;

class fordemo
{
public static void main(String args[])
{
int n;
int sum=0;
for(n=10; n>0; n--)
{
sum=sum+n;
}
System.out.println(“the sum of numbers from 1-10 is”+sum);
}
for example for nested for.. loop.

class multitable
{
public static void main(String args[])
{
int I,j,m=5,j=10;
int prod;
for(I=2; I<=m; I++)
{
System.out.println(“Multiplication table for “ +I);
for(j=1;j<=n; j++)
{
prod=j*I;
System.out.println(j + “X”+I + “= “+prod);
} } } }

Java Nested for Loop

If we have a for loop inside the another loop, it is known as nested for loop. The inner loop
executes completely whenever outer loop executes.

Example:

NestedForExample.java

public class NestedForExample {


public static void main(String[] args)
{
//loop of i
for(int i=1;i<=3;i++){
//loop of j
for(int j=1;j<=3;j++){
System.out.println(i+" "+j);
}//end of i
}//end of j
}
}

ava for-each Loop

The for-each loop is used to traverse array or collection in Java. It is easier to use than simple
for loop because we don't need to increment value and use subscript notation.

It works on the basis of elements and not the index. It returns element one by one in the defined
variable.

Syntax:

for(data_type variable : array_name){


//code to be executed
}

public class ForEachExample {


public static void main(String[] args) {
//Declaring an array
int arr[]={12,23,44,56,78};
//Printing array using for-each loop
for(int i:arr){
System.out.println(i);
}
}
}

Java Jump Statements


1. The break Statement:
The break statement is to be used only in loops and switch statement.
When this statement is executed, the control is taken out of the loop. The loop becomes dead.
Class breakdemo
{

public static void main(String args[])


{
int I;
for(I=1; I<= 100; I++)
{
if(I==10)
{
break;
}
System.out.println(I);
}

} }

2. The continue Statement:

The continue statement is used inside the loop control blocks. When the
continue statement is executed, the control skips the remaining portion
of the loop and goes to the beginning of the loop and continue.

For example;

Class continuedemo
{
public static void main(String args[])
{
int I=0;
while( I <= 10)
{
I++;
if(I==5)
{
continue;
}
System.out.println(I);
} } }

The roots of a quadratic equation

Ax2+bx+c=0;
Is given by
X1= -b+√b2-4ac
X2= -b-√b2-4ac

class rootsquad
{
public static void main(String args[])
{
double a,x,b,c,x1,x2;

b=20;
a=5;
c=4;
x1= ((-b) + Math.sqrt(b*b - 4*a*c)) / 2 * a;
x2= ((-b) - Math.sqrt(b*b - 4*a*c)) / 2 * a;

System.out.println(" X1 is = \t"+x1 + "\n"+ "x2 is =\t"+x2);


}}
Unit – 1 Assignment
Q1. What is variable? Explain the type of variables.
Q2. What is data type in java? Explain the type data type in java with size and range.
Q3. What operator? Explain the type of operators with suitable example.
Q4. What is an array? Explain the types of array with suitable example.
Q6. What is looping ? Explain the following looping with respective example:
For loop, while loop, and do – while loop.
Q7. What jump statement? Explain the jump statements with suitable example.
Q8 . Write a program for simple interest calculation.
Q9. Write a program for sorting numbers in ascending order.
Q10. Write a program for calculating area and perimeter of rectangle.
Q11. Write a program to read temperature in Celsius and convert it into Fahrenheit.
Q12. Write a program to read few numbers into an array and search a number into an
array.
Q13. Write a program for matrix addition.
Q14. Write a program for transpose a matrix.
Q15. Write a program to display a triangle as given below.
*
**
***
****
*****

You might also like