0% found this document useful (0 votes)
11 views28 pages

JAVA-UNIT 1

The document provides an overview of Java programming, focusing on object-oriented concepts such as classes, objects, inheritance, polymorphism, abstraction, and encapsulation. It also covers the history of Java, its key features, and milestones in its development, highlighting its platform independence and object-oriented nature. Additionally, it discusses Java's data types, variables, and arrays, including their declaration, creation, and initialization.

Uploaded by

arul85700
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)
11 views28 pages

JAVA-UNIT 1

The document provides an overview of Java programming, focusing on object-oriented concepts such as classes, objects, inheritance, polymorphism, abstraction, and encapsulation. It also covers the history of Java, its key features, and milestones in its development, highlighting its platform independence and object-oriented nature. Additionally, it discusses Java's data types, variables, and arrays, including their declaration, creation, and initialization.

Uploaded by

arul85700
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/ 28

LOYOLA COLLEGE OF ARTS & SCIENCE ,METTALA

JAVA PROGRAMMING
UNIT - I
Review of Object Oriented Concepts
The main aim of object-oriented programming is to implement real-world
entities, for example, object, classes, abstraction, inheritance,
polymorphism, etc.

OOPs (Object-Oriented Programming System)


Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-Oriented
Programming is a methodology or paradigm to design a program using classes and objects. It simplifies
software development and maintenance by providing some concepts:

o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Object

Any entity that has state and behavior is known as an object. For example, a chair, pen, table, keyboard,
bike, etc. It can be physical or logical.

An Object can be defined as an instance of a class. An object contains an address and takes up some
space in memory. Objects can communicate without knowing the details of each other's data or code.
The only necessary thing is the type of message accepted and the type of response returned by the objects.

Example: A dog is an object because it has states like color, name, breed, etc. as well as behaviors like
wagging the tail, barking, eating, etc.

Class
Collection of objects is called class. It is a logical entity.
A class can also be defined as a blueprint from which you can create an individual object. Class doesn't
consume any space.

Inheritance

When one object acquires all the properties and behaviors of a parent object, it is known as inheritance.
It provides code reusability. It is used to achieve runtime polymorphism.

Polymorphism
If one task is performed in different ways, it is known as polymorphism. For example: to convince the
customer differently, to draw something, for example, shape, triangle, rectangle, etc.

In Java, we use method overloading and method overriding to achieve polymorphism.

Another example can be to speak something; for example, a cat speaks meow, dog barks woof, etc.

Abstraction

Hiding internal details and showing functionality is known as abstraction. For example phone call, we
don't know the internal processing.

In Java, we use abstract class and interface to achieve abstraction.


Encapsulation

Binding (or wrapping) code and data together into a single unit are known as encapsulation. For example,
a capsule, it is wrapped with different medicines.

A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the
data members are private here.

JAVA HISTORY
 Java is a general-purpose, object-oriented programming language developed by Sun
Microsystems of USA in 1991. It was originally called oakby James Gosling, one of the
inventors of the language.
 Java is a platform-neutrallanguage, because this programming language that is not tied to any
particular hardware or operating system. Programs developed in Java can be executed anywhere
on any system.
 The most striking feature of java is
 Platform-independent (neutral) language
 Object oriented language
Platform-neutral:
 Java is the first program language that is not tied to any particular hardware or operating system.
 It can be executed anywhere on any system.
 During the compilation, the compiler converts java program into its generic code language called
byte code.
Object oriented:
 It is a way of organizing programs as collections of objects, which represents an instance of class.
 It includes a set of class library that provides basic data types, system input & output and other
utility functions.

Java Milestones
Year Development
1990 Sun Microsystems decided to develop special software team headed by James Gosling.

1991 After object-oriented language C++, the team announced a new language called "Oak".

1992 Green Project team by Sun demonstrated the application of new language to control a list of
home appliances.
1993 Developing Web applets (tiny programs) by Green Project teams.

1994 The team developed a Web browser called "Hot Java".

1995 Oak was renamed as "Java".

1996 Sun releases Java Development Kit 1.0.

1997 Sun releases Java Development Kit 1.1 (JDK 1.1).

1998 Sun releases Java 2 with version 1.2 of the Software Development Kit 1.1 (SDK 1.2).

1999 Sun releases Java 2 Platform, Standard Edition (J2SE) and Enterprise Edition (J2EE).

2000 J2SE with SDK 1.3 was released.

2002 J2SE with SDK 1.4 was released.

2004 J2SE with JDK 5.0 was released. This is known as J2SE 5.0.
JAVA BUZZWORDS

1. Simple
2. Object-Oriented
3. Distributed
4. Compiled and Interpreted
5. Robust
6. Secure
7. Architecture-Neutral
8. Portable
9. High Performance
10. Multithreaded
11. Dynamic

1. Simple

 Java is designed to be easy for beginners and professional programmers to learn and use
effectively.
 It’s simple and easy to learn if you already know the basic concepts of Object-Oriented
Programming.
 Java has removed many complicated and rarely-used features, such as explicit pointers and
operator overloading.

2. Object-Oriented

 Everything in Java revolves around objects and classes.


 Java allows you to model real-world entities (like a car or a bank account) as objects in your
program, making it easier to manage and build complex applications.
 Key Object-Oriented Programming (OOP) concepts include:

o Object: An instance of a class.


o Class: A blueprint for creating objects.
o Inheritance: Allows one class to inherit the properties of another.
o Polymorphism: The ability of objects to take on multiple forms.
o Abstraction: Hides the complex details and shows only the essentials.
o Encapsulation: Keeps the data safe by restricting access to it.

3. Distributed

 Java is designed to create distributed applications on networks.


 Java applications can access remote objects on the Internet as easily as they can do in the local
system.
 Java enables multiple programmers at multiple remote locations to collaborate and work
together on a single project.

4. Compiled and Interpreted

 Java combines both compiled and interpreted approaches, making it a two-stage system.
 Compiled: Java compiles programs into an intermediate representation called Java Bytecode.
 Interpreted: Bytecode is then interpreted, generating machine code that can be directly
executed by the machine that provides a JVM.
5. Robust

 Java provides many features that make programs execute reliably in a variety of
environments.
 Java is a strictly typed language that checks code at compile time and runtime.
 Java handles memory management with garbage collection and captures serious errors
through exception handling.

6. Secure

 Java does not use pointers, which helps prevent unauthorized memory access.
 The JVM verifies Java bytecode before execution, ensuring that it adheres to Java’s security
constraints.
 Java applications run in a restricted environment (sandbox) that limits their access to system
resources and user data, enhancing security.

7. Architecture-Neutral

 Java language and JVM help achieve the goal of “write once; run anywhere, any time,
forever.”
 Changes and upgrades in operating systems, processors, and system resources do not force
any changes in Java programs.

8. Portable

 Java provides a way to download programs dynamically to various types of platforms


connected to the Internet.
 Java is portable because of the JVM, which provides a consistent runtime environment across
different platforms.

9. High Performance

 Java performance is high because of the use of bytecode.


 The bytecode can be easily translated into native machine code.

10. Multithreaded

 Multithreaded programs handle multiple tasks simultaneously, which is helpful in creating


interactive, networked programs.
 Java run-time system supports multiprocess synchronization for constructing interactive
systems.

11. Dynamic

 Java can link in new class libraries, methods, and objects dynamically.
 Java programs carry substantial amounts of run-time type information, enabling dynamic
linking in a safe and expedient manner.

JVM Architecture
 Java compiler translates source code into byte code for a machine, which is also referred to as
virtual machine code. The java provides an intermediate code called as byte code for a machine.
This machine is called as java virtual machine(JVM).
Figure: Process of Compilation
 The virtual machine code is not machine specific. The machine specific code is generated by the
Java interpreter, by acting as an intermediate between the virtual machine and real machine.

Figure: Process of Converting Byte Code into Machine Code

DATA TYPES
 Every variable in Java has a data type. It also specifies the size and type of values that can be
stored. The variety of data types available allows the programmer to select the type appropriate
to the needs of the application.
Figure: Data Types in Java
Integer Types:
 It can hold whole numbers. The size of the values that can be
stored depending upon the integer type. The long integer is used
by appending the letter L or l at the end of the number. It supports
four type of integers are:
 byte  One byte
 short  Two bytes
 int  Four bytes
 long  Eight bytes
 Java does not support the concept of unsigned types and therefore
all Java values are signed meaning they can be positive or
negative.

Type Size Minimum Value Maximum Value


Byte One byte -128 127
Short Two bytes -32,768 32,767
Int Four bytes -2,147,483,648 2,147,483,647
Long Eight bytes -9,223,372,036,854,775,808 9,223,372,036,854,775,807

Floating Point Types:


 Integer types can hold only whole numbers and therefore we use another type known as floating
point type to hold numbers containing fractional parts such as 27.59 and -1.375.
 It holds fractional parts. There are two kinds of floating point storage in Java.
 The float type values are single-precision numbers while the double types represent double-
precision numbers.
 float  4 bytes
 double  8 bytes
Type Size Minimum Value Maximum Value
float 4 bytes 3.4e-038 1.7e+0.38
double 8 bytes 3.4e-038 1.7e+308
Character Type:
 To store the character constant in memory, the character data type (char) is used. It occupies 2
bytes but it can hold only a single character.
Boolean Type:
 It is used to test a particular condition during the execution of the program. It occupies and uses
only one bit of storage. It takes only two values either true or false.
 All comparison operators return Boolean type values. Boolean values are often used in selection
and iteration statements. The words true and false cannot be used as identifiers.

VARIABLES

 A Variable is an identifier that denotes a storage location used to store a data value. Unlike
constants that remain unchanged during the execution of a program, a variable may take
different values at different times during the execution of the program.
 Variable name can be chosen by the programmer in a meaningful way.
 Example: average, height, classstrength.
Rules:
 They must not begin with a digit.
 Upper case and lower case are distinct.
 It should not be a keyword.
 White space is not allowed.
 It can be of any length.

SCOPE OF VARIABLES
 The area of the program where the variable is accessible is called its scope. The Java variable
classified into three types:
 Instance
 Class
 Local
Instance Variable:
 These variables are declared inside a class. It was created when the objects are instantiated and
associated with the objects. They take different value for each object.
Class Variable:
 These variables are global to a class and belong to the entire set of objects that class creates.
Only one memory location is created for each class variable.
Local Variable:
 The variables declared and used inside the methods are called local variables. It also be declared
inside the program blocks that are defined between an open brace {and a close brace}.

ARRAY
Introduction
 An array is a group of contiguous or related data items that share a common name. Each and
every element of an array is identified using index or subscript number.
Example: employee [10];
Example: salary[10] , It represent the salary of the 10th employee.
Types of Arrays:
 The array consists of the following types:
 One-dimensional Array
 Multi-dimensional Array
One-dimensional Arrays
 A list of items is specified by one variable name using only one subscript is called
single-subscripted or one-dimensional.
Example: int number[] = new int[5];
 Java subscripts start with the value 0.
 The values to the array elements can be assigned as follows:
number[0]=20;
number[1]=30;
number[2]=40;
number[3]=50;
number[4]=60;
CREATING AN ARRAY
 Creation of an array involves three steps.
1. Declare the array.
2. Create memory locations.
3. Put values into the memory location.
Declaration of Arrays
 Arrays in java can be declared in two forms.
Form1: type array_name[];
Form2: type[] array_name;
Example: int number[]; float[] marks;
Creation of Arrays
 After declaring an array, we need to create it in the memory.
array_name=new type[size];
Example: number =new int[5];
Initialization of Arrays:
 The final step is put values into the array created. This process is known as initialization.
Syntax: arrayname[subscript]=value;
Example: a[0]=25; number[4]=30;
 We can also initialize arrays automatically in the same way as the ordinary variables when they are
declared.
Syntax: type arrayname[]={list of values};
Example: int number[]={20,40,50,60};
Array length:
 The length of the array can be determined using length.
e.g., int num[]=new int[5];
int size=num.length; // size=5

Two-dimensional Arrays
 In java, a table of items can be defined using two dimensional arrays.
 It is an array of arrays. The left index determines row and right index determines columns.
It must be initialized with a list of initial values enclosed in braces must initialize the two-
dimensional array.
 We can create a two-dimensional array as
int myarray[][];
myarray=new int[3][4];
Or
int myarray[][]=new int[3][4];
 This will create a table that can store 12 integer values, four across and three down.
Example 1:
int table[2][3] = {0, 0, 0, 1, 1, 1};
int table[][] = {{0, 0, 0}, {1, 1, 1}};

int table[][] = {
{0, 0, 0},
{1, 1, 1}
};
Example 2:
class twoarray
{
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();
}
}
}
VARIABLE SIZE ARRAYS
 Java treats multidimensional array as “arrays of arrays”.
 It is possible to declare a two-dimensional array as follows:
int x[][]=new int[3][];
x[0]=new int[2];
x[1]=new int[4];
x[2]=new int[3];
 These statements create a two-dimensional array as having different lengths for each row.

EXAMPLE:
import java.io.*;
class sample }
{ System.out.println(“”);
public
static void
}
main(String args[]) }
{ }
int a[i] [j] =
{0, 1, 1, 3};
for(i=0;i<2;i++)
{
Output:
for(j=0;j<2;j++) 0 1
{ 1 3
System.out.println(a[i][j]);

OPERATORS
Introduction:
 An operator is a symbol that tells the computer to perform certain mathematical or logical
manipulations. The Java operators can be classified into number of related categories:
 Arithmetic Operators
 Relational Operators
 Logical Operators
 Assignment Operators
 Increment and Decrement Operators
 Conditional Operators
 Bit-wise Operators
 Special Operators
Arithmetic Operators:
 The basic and common operators in computer programming language are Arithmetic operators
also called as Binary operators since they require two operands. They are addition (+),
subtraction (-), multiplication (*), division (/), modulus (%).
 Arithmetic operators cannot be used as Boolean type. It is used to construct mathematical
expressions as in algebra. Java supports the following categories:

Operator Meaning
+ Addition (or) Unary Plus
- Subtraction (or) Unary Minus
* Multiplication
/ Division
% Modulo Division (Remainder)
Integer Arithmetic:
 When both the operands in a single arithmetic expression are integer, the expressions are called
an integer expression and the operation is called integer arithmetic. It always yields an integer
value.
Example:
a = 10 and b = 4
a * b = 40
a%b=2
Real Arithmetic:
 An arithmetic operation involving only real operands is called real arithmetic.
Example: a = 10.5 and b = 5.4 a + b = 15.9
Mixed-Mode Arithmetic:
 When one of the operands is real and the other is integer, the expression is called mixed-mode
arithmetic expression. If either operand is of the real type, then the other operand is converted
to real and the real arithmetic is performed.
Example: a = 25 and b = 20.0 a / b = 1.5
Relational Operators:
 It is used for comparisons between two quantities and depending on their relation, takes certain
decisions.
 The comparison operators are used to compare the values of two variables. These are used in
the program flow. These operators in ‘C’ produce true (1) or false (0) results. These operators
can be grouped as relational and equality operators.
Operator Meaning
< less than
> greater than
<= less than or equal to
>= greater than or equal to
== equal to
!= not equal to
Syntax: ae-1 relational operator ae-2
 In the above syntax, ae-1 and ae-2 are arithmetic expressions, which may be simple constants,
variables or combination of them.

Example:
Operator Meaning
20 < 8 + 5 False
-25 >= 0 False
5.5 <= 10 True
Logical Operators:
 The Java language consists of three logical operators. They are:

Operator Meaning
&& logical AND
|| logical OR
! logical NOT

 The logical operators && and || are used to combining two or more relations, is termed as logical
expression or a compound relational expression.
Truth Table:
op -1 op -2 op - 1 && op – 2 op - 1 || op – 2
True True True True
True False False True
False True False True
False False False False

Assignment Operators:
 It is used to assign the value of an expression to a variable.
Syntax: v op = exp;
 In the above syntax V is a variable, exp is an expression and op is a Java binary operator. The
operator op= is known as shorthand assignment operator.
Advantages:
 What appears on the left-hand side need not be repeated and therefore it becomes easier to write.
 The statement is more concise and easier to read.
 Use of shorthand operator results in a more efficient code.
Example:

Assignment Operator Shorthand Operator


a=a%b a%=b
a = a * (n + 1) a*=n+1
a=a–1 a-=1
a=a+1 a+=1
Increment and Decrement Operators:
 The increment and decrement operators extensively used in for and while loops. The operator
++ adds 1 to the operand while -- subtracts 1.
 It consists of two forms: Postfix and Prefix. In postfix the operator follows the operand. The
prefix form the operator appears before the operand.
Example:
++a; (or) a++;
--a; (or) a--;
++m; is equivalent to m = m + 1;
Conditional Operator:
 The character pair ?: is a ternary operator. It is used to construct conditional expressions of the
form.
Syntax: exp1? exp2: exp3
where exp1, exp2 and exp3 are expressions. The exp1 is evaluated first. If it is true, then the
expression exp2 is evaluated otherwise exp3 is evaluated.

Example:
m = 15; n = 10;
x = (n > m)? n : m;
Example:
If (a>b)
X=a;
Else
X=b;
This may be expressed in ternary condition as follows:
a=10;
b=15;
x=(a>b)?a:b;
Bitwise Operators:
 It is used to test the bits or shifting them to the right to left. It may not be applied to float or
double.
Operator Meaning
& bitwise AND
| bitwise OR
^ bitwise exclusive OR
~ one's complement
<< shift left
Example: >> shift right
1010 0101 (bitwise NOT)
1010 & >>> shift right with zero fill 11111010 (bitwise
AND – produces a 1 bit if both
operands are also 1, otherwise 0)
1010 | 1110 1110 (bitwise OR – produces a 1 bit if either of the bits in the operands is a 1,
otherwise 0)
1010 ^ 1111 0101 (bitwise XOR – produces a 1 bit if exactly one operand is 1, otherwise 0)
Special Operators:
 The Java language contains some special operators. They are: instanceof, dot operator.
Instanceof Operator:
 It is an object reference operator and returns true if the object on the left-hand side is an instance
of the class given on the right-hand side.
Example: person instanceof student
 Is true if the object person belongs to the class student; otherwise it is false.
Dot(.) Operator:
 It is used to access the instance variables and methods of class objects.
Example:
Person2.no // Reference to the variable no
Person2.getdata () // Reference to the method getdata()

CONTROL STATEMENTS

 It consists of the following three types:


 Selection Statement
 Iteration Statement
 Jump Statement

Selection Statement:
 These select one of several control flows. There are three types of selection statements in Java:
 if
 if-else
 switch

Iteration Statement:
 These specify how and when looping will take place. There are three types of iteration statements
in Java:
 while
 do
 for
Jump Statement:
 It passes control to the beginning or end of the current block, or to a labeled statement. It consists
of four types of jump statements:
 break
 continue
 return
 throw

 The Java language supports the following decision making and control statements:
 if Statement
 switch Statement
 Conditional Operator Statement
Decision Making with if Statement:
 The if statement is a powerful decision making statement.
 It is used to control the flow of execution of statements. It is basically two-way decision
statement used within expression.
Syntax: if (test expression)
 The if statement may be implemented in different forms depending on the complexity of
conditions to be tested.
 Simple if Statement
 if…else Statement
 Nested if…else Statement Entry
 else if Ladder
Simple if Statement: True
 The 'statement block' may be a single or group of statements. Test
Expression
 If the test expression is true then 'statement block' will be executed
otherwise statement-x will be executed. Statement-block
False
 When the condition is true both the statement block and the statement
x are executed in sequence. Statement-x
Syntax:

if (test expression)
Next statement
{
statement-block;
} Output:
statement-x;
Example: Largest value is a: 55
import java.io.*;
class first
{
public static void main(String args[ ])
{
int a=55, b= 32;
if (a>b)
{
System.out.println (“Largest value is a:”, +a);
}
}
}

The if-else Statement:


 It is an extension of the simple if statement. If the test expression is true, the true-block
statements are executed, otherwise the false-block statements are executed.
 In both the cases, the control is transferred subsequently to the statement x.
Syntax:
if (test-expression)

Tes
t
exp
ress
True-block stmt False-block stmt

Statement-
x

{
True-block statement(s);
}
else
{
False-block statement(s);
}
Output:
statement-x;
Example: Largest value is b: 32
import java.io.*;
class first1
{
public static void main(String args[ ])
{
int a=25, b= 32
if (a>b)
{
System.out.println(“Largest value is a: ” , +a);
}
else
{
System.out.println(“Largest value is b: ” , +b);
}
}
}

Nesting of if-else Statements:


 When a series of decisions are involved, use more than one if…else statement in nested form as
follows:
 If the condition-1 is false, the statement-3 will be executed; otherwise it continues to
perform the second test.
 If the condition-2 is true, the statement-1 will be evaluated; otherwise the statement-2
will be evaluated and then the control is transferred to the statement-x.
Syntax:
if (test condition-1)
{
if (test condition-2)
{ false true
statement-1; Test
} expressi
else
{
statement-2;
} Stmt-3 false true
Test
} condition

Stmt -2 Stmt-1
else
{
statement-3;
}
statement-x;
Example: Stmt-x
import java.io.*;
class large
{ public static void main(String args[])
{
int a=325, b=712, c=478;
System.out.println(“Largest value is:”);
if(a>b)
{
if(a>c)
{
System.out.println(a);
}
else
{
System.out.println(c);
}
}
else
{
if(c>b)
{
System.out.println(c);
}
else
{
System.out.println(b);
}
}
}
}
The else-if Ladder:
 There is another way of putting ifs together when multipath decisions are involved.
 A multipath decision is a chain of ifs in which the statement associated with each else is an if.
Syntax:
if (condition1)
statement-1;

else if (condition2)
statement-2;
else if (condition3)

statement-3;



else if (condition n)

statement-n;

else

default statement;

statement-x;
 The conditions are evaluated from the top
downwards. As soon as the true condition is
found, the statement associated with it is
executed and the control is transferred to the
statement-x.
 When all the conditions becomes false, then the final else containing default-statement will be
executed.
Example:
if (code == 1)
Color = "Green";
else if (code == 2)
Color = "Red";
else if (code == 3)
Color = "Yellow";
else
Color = "White";
Example:
import java.io.*;
class second
{
public static void main(String args[]) Output:
{ 100 distinction
int rollnumber [] = {100, 101, 102, 103};
int marks[] = {81, 76, 43, 58};
101 Ist class
for (int i =0; i<rollnumber; i++) 102 Fail
{ 103 2nd class
if(marks [i]> 75)
System.out.println(rollnumber[i] +”” distinction );
else if(marks[i] > 55)
System.out.println(rollnumber[i] +”” Ist class);
else if(marks[i] > 45)
System.out.println(rollnumber[i] +”” 2 nd class);
else
System.out.println(rollnumber[i] +”fail”);
}
}
}
The switch Statement:
 Java has a built-in multiway decision statement known as switch. This switch statements test
the value of a given variable against a list of case values and when a match is found, a block of
statements associated with the case is executed.
 The expression is an integer expression or characters. value-1, value-2 are constants or constant
expressions are known as case labels. The block-1, block-2 are statement lists and may contain
zero or more statements. The case labels should ends with a colon (:). The default is an optional
one.
 When the switch is executed, the value of the expression is successively compared against the
values value-1, value-2…..
 If a case is found whose value matches with the value of the expression, then the block of
statements follows the case are executed. The default is an optional case.
 The break statement at the end of each block signals the end of a particular case and cause an
exit from the switch statement, transferring control to the statement-x following the switch.
Syntax:
switch (expression)
{
case value-1:
block-1;
break;
case value-2:
block-2;
break;
….
default:
default-block;
break;
}
statement-x;
Example:
a = (char)System.in.read();
switch(a)
{
case 'M':
case 'm':
System.out.println("Hello");
break;
case 'S':
case 's':
System.out.println("Hai");
break;

case 'B':
case 'b':
System.out.println("Simple");
break;
default:
System.out.println("Java");
break;
}
Example:
import java.io.*;
class letter
{
public static void main(String args[])
{ Output:
char letter; The given alphabet is a vowel
switch (letter)
{
case ‘a’:
case ‘e’:
case ‘i’ :
case ‘o’:
case ‘u’: System.out.println(“The given alphabet is a vowel”);
break:
default: System.out.println(“the given alphabet is not a vowel”);
}
}
}
The ?: Operator:
 It is combination of ? and : and takes three operands.
General Format: conditional expression? expression1: expression2;
 The conditional expression is evaluated first. If the result is true, expression1 is evaluated,
otherwise, expression2 is evaluated and its value is returned.
Example: y = (a < 0)? 0:1;

LOOPING STATEMENTS IN JAVA.


 The Java language provides three constructs for performing loop operations. They are:
 while Statement
 do Statement
 for Statement
The while Statement:
 The simplest of all the looping structures in Java is the while statement. The while is an entry-
controlled loop statement.
 The test condition is first evaluated. If the condition is true the body of the statements are
executed repeatedly until the condition is false.
 The body of the loop may have one or more statements. The braces are needed only if the body
contains two or more statements.
Syntax:

Initialization;

while (test condition)


{
body of the loop
}
Example:
sum = 0; n = 1;
while(n <= 10)
{
sum = sum + n * n;
n = n + 1;
}
System.out.println(sum);
Example:
import java.io.*;
class sample
{
public static void main(String args[]) Output:
{ 1
j=1:
while(j <5)
2
{ 3
System.out.println (j); 4
j= j + 1;
}
}
}
The do Statement:
 In this situation the user will execute body of the loop before the test is performed. The program
to evaluate the body of the loop statement first. At the end of the loop, the test condition is
evaluated. If the condition is true, the program continues to evaluate the body of the loop once
again. This process continues as long as the condition is true.
 When the condition is false, the loop will be terminated, and control goes to the statement that
appears immediately after the while statement.
Syntax:

Initialization;
do
{
body of the loop;
}
while (test condition);
i = 1;
sum = 0;
do
{
sum = sum + i;
i = i + 2;
}
while(sum <50);
Example:
import java.io.*;
class sample1
{
public static void main (String args[])
{ Output:
j=1: 1
do 2
{ 3
System.out.println (j);
j= j + 1;
4
} while(j <4)
}
}
Difference between while and do while
while do-while
It is a looping construct that will execute only if It is a looping construct that will execute at least
the test condition is true. once even if the test condition is false.
It is an entry controlled loop. It is an exit controlled loop.
The for Statement:
 It is another entry-controlled loop that provides a more concise loop control structure. The
execution of statement as follows:
 Initialization of the control variables.
 The value of the control variable is tested using the test condition.
 The variable is incremented using an assignment statement.
Syntax:

for(initialization; test condition; increment)


{

Body of the loop;


}
Example 1:
for(row = 1; row <= n; row++)
{
System.out.println(row);
}
Example 2:
for(x = 9; x >= 0; x = x - 1)
{
System.out.println(x);
}

Additional Features of for Loop:


 More than one variable can be initialized at the time in the for statement, separated by a comma.
The increment section may also have more than one part.
Example 1:
x = 1;
for(n = 1; n < 5; ++n)
can be written as
for (x = 1, n =1; n <5; ++n)
Example 2:
for(n = 1, m = 5; n < m; n = n + 1, m = m - 1)
{
System.out.println(n);
}
Nesting of for Loops:
 The for statement within another for statement is called as nested for loop. The loop with in
another loop is called nested loop.
Example: for(i=1;i<10;i++)
{
……..
……..
for(j=1;j<=5;++j)
{
…….
……
}
………
………
}
Example:
class nesting
{
public static void main (String args[])
{
int i,j;
for(i = 0; i < 10; i++)
{
for(j = 0; j <= i; j++)
{
System.out.print("@ ");
}
System.out.println("");
}
}
}
JUMPS IN LOOPS

 Java permits a jump from one statement to the end or beginning of a loop as well as a jump out of a
loop.
Jumping Out Of a Loop
 The break statement is used for exit from a loop. It is used within while, do or for loops.
Syntax: break;
Example:
i=0;
while(i<=10) Output
{ 1
2
3
4
i=i+1;
if(i==5)
break;
System.out.println(i);}

Skipping A Part Of A Loop


 This statement causes the loop to be continued with the next iteration after skipping any statement in
between.
Syntax:continue; Output
Example:
i=0;
1
while(i<=10) 2
{ 3
i=i+1; 4
if(i==5) 6
continue;
System.out.println(i);
7
} 8
9
10

TYPE CONVERSION ANS CASTING


Type conversion is of two types based on how the conversion is performed: 1) Implicit
conversion (also known as automatic conversion or coercion), 2) Explicit conversion (also known as
type casting).

Implicit Conversion or Coercion


This type of conversion is performed automatically by Java due to performance reasons. Implicit
conversion is not performed at all times.

There are two rules to be satisfied for the conversion to take place. They are:

1. The source and destination types must be compatible with each other.
2. The size of the destination type must be larger than the source type.

For example, Java will automatically convert a value of byte into int type in expressions since they are
both compatible and int is larger than byte type.

Since a smaller range type is converted into a larger range type this conversion is also known
as widening conversion. Characters can never be converted to boolean type. Both are incompatible.

Explicit Conversion or Casting

There may be situations where you want to convert a value having a type of size less than the
destination type size. In such cases Java will not help you. You have do it on your own explicitly. That
is why this type of conversion is known as explicit conversion or casting as the programmer does this
manually.

Syntax for type casting is as shown below:

(destination-type) value

An example for type casting is shown below:

int a = 10;
byte b = (byte) a;

In the above example, I am forcing an integer value to be converted into a byte type. For type casting
to be carried out both the source and destination types must be compatible with each other. For
example, you can’t convert an integer to boolean even if you force it.

In the above example, size of source type int is 32 bits and size of destination type byte is 8 bits. Since
we are converting a source type having larger size into a destination type having less size, such
conversion is known as narrowing conversion.

A type cast can have unexpected behavior. For example, if a double is converted into an int, the
fraction component will be lost.

Type promotion in expressions


In addition to assignment statements, there is another place where type conversion can occur. It is in
expressions. An expression is a collection of variables, values, operators and method calls which
evaluate to a single value.
Type promotion rules of Java for expressions are listed below:

 All char, short and byte values are automatically promoted to int type.
 If at least one operand in an expression is a long type, then the entire expression will be
promoted to long.
 If at least one operand in an expression is a float type, then the entire expression will be
promoted to float.
 If at least one operand in an expression is a double type, then the entire expression will be
promoted to double.

To understand the above type promotion rules let’s consider the following example of expression
evaluation:

classSample{
publicstaticvoidmain(String[] args)
{
int i =1000000;
char c ='z';
short s =200;
byte b =120;
float f =3.45f;
double d =1.6789;
double result =(f * b)+(i / c)-(d * s);
System.out.println("Result = "+result);
}}

Output of the above program is: Result = 8274.22

In the above program the expression is (f * b) + (i / c) – (d * s). In the first sub expression (f * b), as
one operand is float, the result of the expression will be a float. In the second sub expression (i / c),
char type will be promoted to int and the result of the expression will be an int. In the third sub
expression (d * s), as one operand is double, the result of the expression is a double.

SIMPLE JAVA PROGRAM


 The below simple program that prints a text as output.
class simple
{
public static void main (String args[])
{
System.out.println("WELCOME");
System.out.println("TO JAVA PROGRAMMING");
}
}
Class Declaration:
 The above example class is a keyword, everything must be placed inside the class. The simple
is a Java identifier that specifies the name of the class to be defined.
Opening Brace:
 Every class definition in Java begins with an opening brace "{" and ends with a matching closing
brace "}"
The Main Line:
The third line contains
public static void main (String args[])
 The main method contains the following keywords:
 public
 static
 void
public:
 It is an access specifier, accessible to all other classes. This is similar to the C++ public modifier.
static:
 Declare the main method always as static because the interpreter uses this method before any
objects are created. It belongs to the entire class and not a part of any objects of the class.
void:
 The type modifier voidstates that the main method does not return any value.
The Output Line:
 The above program only one executable statement.
System.out.println("java is betterthan c++");
 The method printlnalways appends a newline character to the end of the string. Every Java
statement must end with a semicolon.
JAVA PROGRAM STRUCTURE
13. EXPLAIN THE GENERAL STRUCTURE OF JAVA PROGRAM. (PART-B)
 A Java program may contain many classes of which only one class defines a main method, one
or more sections.

Documentation Section:
 This section consists of set of comment lines giving the name of the program, the author and
other details. Java also uses a third style of comment /* *…*/ known as documentation
comment.
 Comments must explain why and what classes and how of algorithms.
Package Statement:
 The first statement in Java is a package statement, declares a package name and informs the
compiler that the classes defined belong to this package.
Example:
 package employee;
Import Statements:
 After the package statement may be a number of import statements. This is similar to the
#include statement in C.
Example:
import employee.test;
 This statement instructs the interpreter to load the test class contained in the package employee.
Interface Statements:
 It is like a class but includes a group of method declarations. It is used to implementing multiple
inheritance features in the program.
 This is an optional section and it is used only when we wish to implement the multiple
inheritance.
Class Definitions:
 A Java program may contain multiple class definitions. These classes are used to map the
objects of real-world problems. The number of classes used depends on the complexity of the
problem.
Main Method Class:
 Every Java stand-alone program requires a main method. It creates objects of various classes
and establishes communications between them.
CONSTRUCTORS
A constructor is a special method which has the same name as class name and that is used
to initialize the objects (fields of an object) of a class. A constructor has the following characteristics:

1. Constructor has the same name as the class in which it is defined.


2. Constructor doesn’t have a return type, not even void. Implicit return type for a constructor is
the class name.
3. Constructor is generally used to initialize the objects of a class.

Syntax for creating a constructor is as shown below:

ClassName([ParametersList]){
//Code of the constructor}

Use of Constructors
A constructor is used for initializing (assigning values to fields) the objects of a class.

Constructor Invocation
A constructor is invoked (called) automatically whenever an object is created using the new keyword.

Types of Constructor
Based on the number of parameters and type of parameters, constructors are of three types:

1. Parameter less constructor or zero parameter constructor


2. Parameterized constructor
3. Copy constructor

Parameter less constructor: As the name implies a zero parameter constructor or parameter less
constructor doesn’t have any parameters in its signature. These are the most frequently found
constructors in a Java program. Let’s consider an example for zero parameter constructor:

class Square

int side;

Square()

side = 4;
}

Parameterized constructor: This type of constructor contains one or more parameters in its signature.
The parameters receive their values when the constructor is called. Let’s consider an example for
parameterized constructor:

class Sqaure

int side;

Square(int s)

side = s;

Copy constructor: A copy constructor contains atleast one parameter of reference type. This type of
constructor is generally used to create copies of the existing objects. Let’s consider an example for
copy constructor:

class Sqaure
{
int side;
Square()
{
side = 4;
}
Square(Square original) //This is a copy constructor
{
side = original.side;
}
}
METHODS

A method is a piece of code to solve a particular task. A method is analogous to functions in C and
C++. Methods are defined inside a class. The syntax for creating a method is as shown below:

The return_type specifies the type of value that will be returned by the method. The name of the
method is specified by method_name. Every parameter in the parameters list follows
the below syntax:
datatype parameter_name

STATIC BLOCKS
A static block is a block of statements prefixed with static keyword. The syntax for creating a static
block is shown below:

static
{
//Statements
}

STATIC DATA

When a variable is declared static in Java programming, it means that the variable belongs
to the class itself rather than to any specific instance of the class. This means that there is only one copy
of the variable in memory, regardless of how many instances of the class are created.

STATIC METHODS STRINGS AND STRING BUFFER CLASS:

StringBuffer is a class in Java that represents a mutable sequence of characters. It provides an


alternative to the immutable String class, allowing you to modify the contents of a string without
creating a new object every time.

Here are some important features and methods of the StringBuffer class:

 StringBuffer objects are mutable, meaning that you can change the contents of the buffer
without creating a new object.
 The initial capacity of a StringBuffer can be specified when it is created, or it can be set later
with the ensureCapacity() method.
 The append() method is used to add characters, strings, or other objects to the end of the buffer.
 The insert() method is used to insert characters, strings, or other objects at a specified position in
the buffer.
 The delete() method is used to remove characters from the buffer.
 The reverse() method is used to reverse the order of the characters in the buffer.
public class StringBufferExample {
public static void main(String[] args)
{
StringBuffer sb = new StringBuffer();
sb.append("Hello");
sb.append("");
sb.append("world");
String message = sb.toString();
System.out.println(message);
}
}

Output
Hello world.

------------------------------------UNIT 1 COMPLETED-----------------------------------------

You might also like