0% found this document useful (0 votes)
67 views

Unit-1 Java

James Gosling and others at Sun Microsystems began developing a language called Oak in 1990 to control devices like cable boxes and PDAs. They renamed it Java and shifted its focus to internet applications as the web grew. Java became popular for developing enterprise applications due to its platform independence, security features, and object-oriented design. It supports features like automatic memory management, exception handling, and networking capabilities.

Uploaded by

pkoppula59
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
67 views

Unit-1 Java

James Gosling and others at Sun Microsystems began developing a language called Oak in 1990 to control devices like cable boxes and PDAs. They renamed it Java and shifted its focus to internet applications as the web grew. Java became popular for developing enterprise applications due to its platform independence, security features, and object-oriented design. It supports features like automatic memory management, exception handling, and networking capabilities.

Uploaded by

pkoppula59
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 49

History of Java

Around 1990 James Gosling , Bill roy and others at Sun Microsystems began
developing a language called Oak. They wanted it primarily to control
microprocessors embedded in consumer items such as cable set-top
boxes,VCR's, toasters, and also for personal data assistants (PDA).

To serve these goals, Oak needed to be:

o Platform independent (since multiple manufacturers involved)


o Extremely reliable
o Compact

The main problem with c and c++ is they are designed to be compiled for a
specific target(CPU)

Then the Internet and Web explosion began, so Sun shifted the target market
to Internet applications and changed the name of the project to Java.

By 1994 Sun's HotJava browser appeared. Written in Java in only a few


months, it illustrated the power of applets, programs that run within a
browser, and also the capabilities of Java for speeding program development

Applets became popular and remain common but don't dominate interactive
or multimedia displays on web pages.

So Java has not succeeded at development of consumer applications.


However, Java's capabilities grew with the release of new and expanded
versions (see below) and it became a very popular language for development
of enterprise, or middleware, applications such as on line web stores,
transactions processing, database interfaces, and so forth and also java was
succeeded well in mobile applications also.
What is Java?

The term Java actual refers to more than just a particular language like C or
Pascal. Java encompasses several parts, including :

 A high level language – the Java language is a high level one that at a
glance looks very similar to C and C++ but offers many unique features
of its own.

 Java bytecode - a compiler, such as Sun's javac, transforms the Java


language source code to bytecode that runs in the JVM.
 Java Virtual Machine (JVM) – a program, such as Sun's java, that runs
on a given platform and takes the bytecode programs as input and
interprets them just as if it were a physical processor executing machine
code.

The Java virtual machine is the cornerstone of the Java and Java 2 platforms.
It is the component of the technology responsible for its hardware- and
operating system- independence, the small size of its compiled code, and its
ability to protect users from malicious programs

The Java virtual machine knows nothing of the Java programming language,
only of a particular binary format, the class file format. A class file
contains Java virtual machine instructions (or bytecodes) and a symbol table,
as well as other ancillary information
For the sake of security, the Java virtual machine imposes strong format and
structural constraints on the code in a class file. However, any language
with functionality that can be expressed in terms of a valid class file can be
hosted by the Java virtual machine. Attracted by a generally available,
machine-independent platform, implementors of other languages are turning
to the Java virtual machine as a delivery vehicle for their languages

The JVM is an imaginary CPU for which most Java compilers emit code.
Support for this imaginary CPU is what allows Java programs to run without
being recompiled on different CPUs. Nothing in the Java programming
language requires Java source code to be compiled into code for the JVM
instead of into native object code.

Versions of Java

Below is a timeline of the different versions of the basic, or Standard Edition


(SE), of Java along with some of the new features that each one introduced.
This edition contains the core language packages (the name for code libraries
in Java) and is aimed for desktop programming.

 1995: Version 1.0 of the Java Development Kit (JDK) was released for
free by Sun.
o 8 packages with 212 classes
o Netscape 2.0-4.0 included Java 1.0.
o Microsoft and other companies licensed Java.
 1997: Version 1.1:
o 23 packages - 504 classes
o Improvements include better event handling, inner classes,
improved JVM.
oMicrosoft developed its own 1.1. compatible Java Virtual Machine
for the Internet Explorer.
o Many browsers in use are still compatible only with 1.1.
o Swing packages of greatly improved graphics became available
during this time but not included with the core language.
 1999: Version 1.2, also called the Java 2 Platform
o 59 packages - 1520 classes
o Code and tools distributed as The Software Development Kit
(SDK)
o Java Foundation Classes (JFC), based on Swing, for improved
graphics and user interfaces, now included with the core
language.
o Collections API included support for various lists, sets, and hash
maps.
 2000: Version 1.3:
o 76 packages - 1842 classes
o Performance enhancements including the Hotspot virtual
machine.
 2002: Version 1.4:
o 135 packages - 2991 classes
o Improved IO, XML support, etc.
 2004: Version 1.5 (previously numbered 1.5):
o 165 packages, over 3000 classes
o Faster startup and smaller memory footprint
o Metadata
o Formatted output
o Generics
o Improved multithreading features

Features

Here we list the basic features that make Java a powerful and popular
programming language:
 Platform Independence
o The Write-Once-Run-Anywhere ideal has not been achieved
(tuning for different platforms usually required), but closer than
with other languages.
o Platform independence means both operating system independent
and hardware independent.

 Object Oriented

Because java supports oops it supports the features of oops such as

1. Data encapsulation.
2. Data abstraction
3. Inheritance
4. Polymorphism

Object oriented throughout - no coding outside of class definitions,


including main()

o An extensive class library available in the core language packages.

 Compiler/Interpreter Combo
o Code is compiled to bytecodes that are interpreted by a Java
virtual machines (JVM) .
o This provides portability to any machine for which a virtual
machine has been written.
o The two steps of compilation and interpretation allow for
extensive code checking and improved security.
 Robust
o Exception handling built-in, strong type checking (that is, all data
must be declared an explicit type), local variables must be
initialized.
 Several dangerous features of C & C++ eliminated:
o No memory pointers
o No preprocessor
o Array index limit checking
 Automatic Memory Management
o Automatic garbage collection - memory management handled by
JVM.
 Security
o No memory pointers
o Programs runs inside the virtual machine sandbox.
o Array index limit checking

 Dynamic Binding
o The linking of data and methods to where they are located, is
done at run-time.
o This differs from C++, which uses static binding. This can result
in fragile classes for cases where linked code is changed and
memory pointers then point to the wrong addresses.
 Good Performance
o Interpretation of bytecodes slowed performance in early versions,
but advanced virtual machines with adaptive and just-in-time
compilation and other techniques now typically provide
performance up to 50% to 100% the speed of C++ programs.
 Threading
o Lightweight processes, called threads, can easily be spun off to
perform multiprocessing.
o Can take advantage of multiprocessors where available
o Great for multimedia displays.
 Built-in Networking
o Java was designed with networking in mind and comes with many
classes to develop sophisticated Internet communications.

Features such as eliminating memory pointers and by checking array limits


greatly help to remove program bugs. The garbage collector relieves
programmers of the big job of memory management. These and the other
features can lead to a big speedup in program development compared to C/C+
+ programming
Programming Tools

You can choose from essentially two different programming environments for
Java:

 Manual - with your favorite text editor (see below) create the Java
source code files (*.java) and then use the command line tools in the
Java Software Development Kit (SDK). The SDK is provided by Sun for
several platforms and includes a number of tools, the most important of
which are:

o javac - compiles Java source code files (e.g. Test.java) to bytecode


files (e.g. Test.class) *
o java - runs Java application programs (i.e. implements the JVM
for the Java programs.)
o appletviewer - tests applets independently of a browser.
 Integrated Development Environment (IDE) - graphical user interface
programming environments (often called GUI Builders) are elaborate,
programs that allow you to interactively build graphical interfaces, edit
the code, execute and run the applets and applications all within the
IDE system. Example Java IDEs include:
o NetBeans - free, open source Java IDE - can be installed along
with the SDK.
o Borland JBuilder - proprietary but the personal version is free
with registration

Java Naming Conventions


Class identifiers begin with a capital letter. Internal words are
capitalized. Other letters are lowercase.

Variable identifiers start with a lowercase letter. Internal words


are capitalized. Other letters are lowercase.

Constant identifiers consist of all capital letters. Internal words


are separated by an underscore (_).

Method identifiers start with a lowercase letter. Internal words


are capitalized. Other letters are lowercase.

Examples:

// class identifier
public class MyClass

// variable identifier
int totalGrades;

// constant identifier
final double TAX_RATE = .05

// JOptionPane is a class; showMessageDialog is a


method
JOptionPane.showMessageDialog( null, "All is well"

Types of Java Applications

There are three types of Java application:

 Java Console Applications


 Java GUI Applications
 Java Applets
 Java Servlets
Java Console Applications:

These are the applications which are much similar as traditional


programming languages such as c and c++.
These are the applications without using GUI.

Limited user interaction

 Applications that run in the background


 Quick test applications to try out techniques in Java

Limitations of a Console Application

 No mouse support
 No graphical/window support
 No additional windows

Examples of background applications include:

 Anti-virus programs that scan while the user is using the computer
Java GUI Applications:

These are the applications which supports the GUI by the creative use of
AWT and Swings .
Java allows you to create a GUI application that takes advantage of a rich set
of window and control types. If you are going to create an application that the
user works directly with, you will most likely want to create a GUI
application.

When to use a GUI Application

 Working directly with the user


 Applications that must display graphical information

Limitations of a GUI Application

 More complex to setup than console application


 Less convenient to run in the background

Java Applets

These are the programmes which are run with in a separate web
browser.
These are used to create small Graphical effects in Internet.

Java Applets allow you to imbed a program directly into a browser. The user
simply has to visit your website to view the applet. Applets can be used to
display graphics, animation and produce sound/music. Applets can be very
useful for displaying advertisements on web sites or providing a greater deal
of interactivity than an HTML page alone can provide

When to use a Java Applet

 When your application should run directly with a website


 When your application enhances the use of a website
 Applications that display animation that should be quickly accessed
form a website

Limitations of a Java Applet

 Applets cannot save data to the user’s disk


 Applets can not make use of the latest Java technology on Internet
Explorer
Java packages

 A package is knothing but the collection of following kinds of types.


o Classes
o Interfaces
o Enumerated types

Package java.lang :

Provides classes that are fundamental to the design of the Java programming
language.

Package java.io

Provides for system input and output through data streams, serialization and
the file system.

Package java.util

Contains the collections framework, legacy collection classes, event model,


date and time facilities, internationalization, and miscellaneous utility classes
(a string tokenizer, a random-number generator, and a bit array).

Package java.applet
Provides the classes necessary to create an applet and the classes an applet
uses to communicate with its applet con

Package java.awt

Contains all of the classes for creating user interfaces and for painting
graphics and imagestext

Package java.net

Provides the classes for implementing networking applications.

Package javax.swing

Provides a set of "lightweight" (all-Java language) components that, to the


maximum degree possible, work the same on all platforms.

Package java.sql

Provides the API for accessing and processing data stored in a data source
(usually a relational database) using the JavaTM programming language

Package java.rmi

Provides the classes and interfaces which are required for RMI (Remote
Method Invocation)package.
Package java.beans

Contains classes related to developing beans -- components based on the


JavaBeansTM architecture

Package java.text

Provides classes and interfaces for handling text, dates, numbers, and
messages in a manner independent of natural languages

Simple programme syntax

Class classname
{
public static void main(String args[])
{
statements;
}
}

Example

Open a file namely HelloWorld.java then write the programme as

Class HelloWorld
{
public static void main(String ar[])
{
System.out.println(“welcome to java world”);
}
}

Compile your Application:

javac HelloWorld.java

Run your Application

java HelloWorld

Tokens Of Java
In a Java program, all characters are grouped into symbols called tokens.
Larger language features are built from the first five categories of tokens

We will examine the kinds of tokens in more detail below,.

1. Idenames the programmer chooses


2. Kentifiers: keywords: names already in the programming language
3. Separators (also known as punctuators): punctuation characters and
paired-delimiters
4. Operators: symbols that operate on arguments and produce results
5. Literals (specified by their type)
o Numeric: int and double
o Logical: boolean
o Textual: char and String
o Reference: null
6. Comments
o Line
o Block

The first category of token is an Identifier. Identifiers are used by


programmers to name things in Java: things such as variables, methods,
fields, classes, interfaces, exceptions, packages, etc.

Java identifiers must be prepared by the following combination of


characters
1.Alphabets.
2.Numbers(0-9)
3._(underscore)
4Although identifiers can start with and contain the $ character,

Keywords

The second category of token is a Keyword, sometimes called a reserved word.


Keywords are identifiers that Java reserves for its own use. These identifiers
have built-in meanings that cannot change

The following is a list of all 49 Java keywords


abstract continue goto package Switch
assert default if private This
boolean do implements protected Throw
break double import public throws
byte else instanceof return transient
case extends int short try
catch final interface static void
char finally long strictfp volatile
class float native super while
const for new synchronized

Notice that all Java keywords contain only lower-case letters.

Separators

The third category of token is a Separator (also known as a punctuator).


There are exactly nine, single character separators in Java, shown in the
following simple EBNF rule.
Java supports the following separators.

; , . ( ) { } [ ]

Operators
An operator is a symbol which performs a particular operation.
Java supports all the types of operators supported in c language.

In addition to operators in c java supports the following operators.


The keywords instance of and new are also considered operators in Java.

Types and Literals

Java supports the following types of literals.

int Literals

An integer literal must be a round value either it may be positive ,


negative and zero.

Eg: int n=100;

double Literals

a double literal is one which consists of fraction part either it may be


positive and nagative.

Eg double db: =12.345;

boolean Literals

A Boolean literal may be either true or false.


Eg: Boolean b=true;

char Literals
A char literal may be a single alphabet (either capital alphabet or
small alphabet).it must be represented in single quotes.

Eg: char ch=’p’;

String Literals

A string literal is a sequence of characters which are represented in


double quotes.

Eg:String st=”welcome”;

Float Literals:

Float literal must be a fraction value which must be ended with f


at the end of the value.

Float ft=12.34f;

Comments :

They are the un executable lines in a programme.

Java includes two style for comments.

 Line-Oriented: begins with // and continues until the end of the line.
 Block-Oriented: begins with /* and continues (possibly over many lines)
until */ is reached.
Escape Sequences:

Escape
Meaning
Sequence
\n new line
\t horizontal tab
\v vertical tab
\b backspace
\r carriage return
\f form feed
\a bell
\\ \ (needed to denote \ in a text literal)
' (does not act as the right ' of a char
\'
literal)
" (does not act as the right " of a String
\"
literal)

data type:

The type of the data that is required for a particular programme.


Java supports two types of data types .

1.primitive data types


2.abstract data types.

Java has eight primitive types of data: byte, int, char, float, double, and
boolean.

Table 3.1 Primitive Data Types in the Java Language

Type Description

boolean true or false.

byte 8-bit twos-complement integer with values between –27 and 27–1 (–
128 to 127).

short 16-bit twos-complement integer with values between –215 and 215–1
(–32,768 to 32,767).

char 16-bit Unicode characters from \u0000 to \uFFFF. For


alphanumerics, these are the same as ASCII with the high byte set to
0.

int 32-bit twos-complement integer with values between –231 and 231–1
(–2,147,483,648 to 2, 147,483,647).

long 64-bit twos-complement integer with values between –263 and 263–1
(–9,223,372,036,854,775,808 to 9,223,372,036,854,775,807).

float 32-bit single precision floating-point numbers using the IEEE 754-
1985 standard (+/– about 10power39).
double 64-bit double precision floating-point numbers using the IEEE 754-
1985 standard (+/– about 10power317).

Default values for primitives and references

Type Default Value


boolean false
byte 0
short 0
int 0
long 0L
char \u0000
float 0.0f
double 0.0d
object reference null

Abstract data type

The data types which are designed by using data abstraction is called
abstract data type.

Eg: Classes, interfaces, and arrays are known as reference types in Java.

Output statement in java:


Package: java.lang
Class : System

public final class System extends Object

The System class contains several useful class fields and methods. It cannot
be instantiated.

Field:

static PrintStrea out


m The "standard" output stream.

Package : java.io

Class : PrintStream

public class PrintStream extends FilterOutputStream

A PrintStream adds functionality to another output stream, namely the


ability to print representations of various data values conveniently

Method : println()

Print a String and then terminate the line

Syntax:

Public void println(java.lang.String);

Write an example to initialize all data types and display them


class DataType1

public static void main(String ar[])

int n=10;

char ch='p';

float ft=12.345f;

double db=567.89;

System.out.println("Given int value is:"+n);

System.out.println("Given char value is:"+ch);

System.out.println("Given float value is:"+ft);

System.out.println("Given double value is:"+db);

java.io package:
Class Data Input Stream:

This class consists of methods and interfaces which are required for reading
data from the keyboard

Constructor Summary
DataInputStream(InputStream obj)
Creates a DataInputStream that uses the specified underlying
InputStream

ReadLine():

This method is used to read data from the keyboard in string format.

Syntax:

Public final java.lang.String readLine() throws java.io.IOException.


java.io package:

Class Integer:

public final class Integer extends Number implements Comparable

The Integer class wraps a value of the primitive type int in an object. An
object of type Integer contains a single field whose type is int.

ParseInt():

public static int parseInt(String s) throws NumberFormatException

Parses the string argument as a signed decimal integer

2.Write an example to read data from the keyboard.

import java.io.*;

class DataType2

public static void main(String ar[])throws IOException


{

int n;

float ft;

DataInputStream dis=new DataInputStream(System.in);

System.out.println("Enter any int value:");

n=Integer.parseInt(dis.readLine());

System.out.println("Enter any float value:");

ft=Float.parseFloat(dis.readLine());

System.out.println("Given int value is:"+n);

System.out.println("Given float value is:"+ft);

Operators in java:

Java supports the following types of operators.

1.Arithmetic Operators:

these operators are used to perform the arithmetic calculations.


Java support the following types of operators.
+ (Addition)
- (Subtraction)
* (Multiplication)
/ (Division)
% (Modulus)
2. Comparison Operators

these operators are used to compare two or more values or variables


or expressions
java supports the following types of comparison operators.

< (less than)


> (greater than)
<= (less than or equals to)
>= (Greater than or equals to)
== (Equals to)
!= (Not equals to)

3. Assignment Operators

These operators are used assign values to variables or expressions.

Java supports two types of assignment operators

1.simple assignment operators

= (equals to)

2.compound assignment operators

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

4.Increment & Decrement Operators

Increment operators:
These operators are used to increment the given value by one

Java supports two types of increment operators


1)pre increment operators
2)post increment operators

Decrement operators:
These operators are used to decrement the given value by one.

Java supports two types of decrement operators

1)pre decrement operators


2)post decrement operators

5.Boolean Operators (or) Logical operators

Conditional
&&
AND
Boolean
&
AND
Conditional
||
OR
Boolean
|
OR
Boolean
!
NOT
Boolean
^
XOR
6.Conditional operator

this operator is used to built a conditional expression. this is the


combination of ? and :

syntax:

Exp1?(Exp2):Exp3;

Here first Exp1 is evaluated if it is true then Exp2 is evaluated


otherwise Exp3 is evaluated.

Class and Object Operators

The first operand must be an object


reference.
c is the name of a class or interface.
Class Test
x instanceof c If x is an instance of type c or a subclass
Operator of c, then true returned.
If x is an instance of interface type c or
a sub-interface, then true is returned.
Otherwise, false is returned.
Class Create an instance of class c using
New c(args)
Instantiation constructor c(args)
Access a method or field of a class or
Class Member object :
"."
Access o.f - field access for object o
o.m() - method access for object o
() Method Parentheses after a method name
Invocation invokes
(i.e. calls) the code for the method, e.g.
o.m()
o.m(x,y)
Treat an object as the type of class or
interface c:
Object
(c) c x=(c)y;
Cast
Treat y as an instance of class or
interface c
This binary operator will concatenate
one string to another. E.g.

String str1 = "abc";


String str2 = "def";
String str3 = str1 + str2

results in str3 holding "abcdef".

For mixed operands, if either a or b in


String
+ (a + b) is a string, concatenation to a
Concatenation string will occur. Primitives will be
converted to strings and the toString()
methods of objects will be called.

(This is the only case of operator


overloading in Java.)

Note that the equivalence operator


"+=" will also perform string
concatenation.
[] Array In Java, arrays are classes. However,
Element the bracket operators work essentially
Access the same as in the C/C++.

To access a given element of an array,


place the number of the element as an
int value (long values cannot be used in
Java arrays) into the brackets, e.g.

float a = b[3];
int n = 5;
char c=c[n];

where b is a float array and c is a char


array.

Examples on operators:

Arithmetic operators:

import java.io.*;

class Operator1

public static void main(String ar[])throws IOException

int a,b;

DataInputStream dis=new DataInputStream(System.in);

System.out.println("Enter any a value:");

a=Integer.parseInt(dis.readLine());

System.out.println("Enter any b value:");

b=Integer.parseInt(dis.readLine());
System.out.println("Sum of given two values is:"+(a+b));

System.out.println("Subtraction of given two values is:"+(a-b));

System.out.println("Multiplication of given two values is:"+(a*b));

System.out.println("Division of given two values is:"+(a/b));

System.out.println("Modulus of given two values is:"+(a%b));

Example on increment & decrement operators

class Operator2

public static void main(String ar[])

int a=10;

int b=a++;

System.out.println("a value is:"+a);

System.out.println("b value is:"+b);

a=10;

b=++a;

System.out.println("a value is:"+a);

System.out.println("b value is:"+b);


}

class Operator3

public static void main(String ar[])

int a=10;

int b=a++;

System.out.println("a value is:"+a);

System.out.println("b value is:"+b);

a=10;

b=++a;

System.out.println("a value is:"+a);

System.out.println("b value is:"+b);

Example on bitwise operators


class Operator4

public static void main(String ar[])

int a=4,b=5;

System.out.println("a&b value is:"+(a&b));

System.out.println("a|b value is:"+(a|b));

System.out.println("a^b value is:"+(a^b));

Example on Bitwise shift operators

class Operator5

public static void main(String ar[])

int a=4;

System.out.println("a<<2 value is:"+(a<<2));

System.out.println("a>>2 value is:"+(a>>2));

}
Example on Ternary Operator(or)Conditional Operator

import java.io.*;

class Operator2

public static void main(String ar[])throws IOException

int a,b,max;

DataInputStream dis=new DataInputStream(System.in);

System.out.println("Enter any a value:");

a=Integer.parseInt(dis.readLine());

System.out.println("Enter any b value:");

b=Integer.parseInt(dis.readLine());

max=(a>b)?a:b;

System.out.println("Maximum value is:"+max);

Control Statements In Java

Control Statements are elements in Source Code that control the flow of
program execution.

Java supports three types of control statements in java as described


below.
1.Conditional control statements.
2.Unconditional control statements.
3.Loop control statements.

Conditional control statements.

They are nothing but the decision making control statements.

Java supports 5 types of Conditional control statements.


1.if
2.if-else
3.nested if
4.else if
5.switch

1.if control statement

it is a simple decision making control statement.

Syntax:
If(exp)
{
statements;
}

2.if-else control statement


it is the extension of simple if control statement.
Syntax

If(exp)
{
statements-1;
}
else
{
statements-2;
}
3.nested if control statement

it is a multiple decision making control statement.

Syntax

If(Exp-1)
{
if(Exp-2)
{
|
|
if(Exp-n)
{
statements;
}
}
}

4.else-if control statement

it is also multiple decision control statements.

If(Exp-1)
{
statements-1;
}
else if(Exp-2)
{
statements-2;
}
else if(Exp-3)
{
statements-3;
}
|
|
|
|
else
{
statements-n;
}

5.switch control statement

it is a multi way decision making control statement which is used to


select one alternate among the many others.

Syntax:

Switch(var(or)Exp)
{
case value-1:
statements-1;
break;
case value-2:
statements-2;
break;
|
|
|
|
|
default:
default block statements;
}

Examples on Control Statements

Example 1:

import java.io.*;

class Condi1

{
public static void main(String ar[])throws IOException

int a,b,c,max;

DataInputStream dis=new DataInputStream(System.in);

System.out.println("Enter any a value:");

a=Integer.parseInt(dis.readLine());

System.out.println("Enter any b value:");

b=Integer.parseInt(dis.readLine());

System.out.println("Enter any c value:");

c=Integer.parseInt(dis.readLine());

if(a>b)

if(a>c)

max=a;

else

max=c;

else

if(b>c)

max=b;
else

max=c;

System.out.println("Maximum value is:"+max);

Example 2:

import java.io.*;

class Condi2

public static void main(String sr[])throws IOException

int a,b,c,max;

DataInputStream dis=new DataInputStream(System.in);

System.out.println("Enter any a vlaue:");

a=Integer.parseInt(dis.readLine());

System.out.println("Enter any b vlaue:");

b=Integer.parseInt(dis.readLine());

System.out.println("Enter any c vlaue:");

c=Integer.parseInt(dis.readLine());
if((a>b)&&(a>c))

max=a;

else if(b>c)

max=b;

else

max=c;

System.out.println("Maximum value is:"+max);

Example on Switch control statement

import java.io.*;

class Switch1

public static void main(String ar[])throws Exception

int a,b,opt;

DataInputStream dis=new DataInputStream(System.in);

System.out.println("Enter any a value:");

a=Integer.parseInt(dis.readLine());
System.out.println("Enter any b value:");

b=Integer.parseInt(dis.readLine());

System.out.println("Enter ur option:");

opt=Integer.parseInt(dis.readLine());

switch(opt)

case 1:

System.out.println("Addition of given two values is:"+


(a+b));

break;

case 2:

System.out.println("Subtraction of given two values is:"+


(a-b));

break;

case 3:

System.out.println("Multiplication of given two values


is:"+(a*b));

break;

case 4:

System.out.println("Division of given two values


is:"+(a/b));

break;
case 5:

System.out.println("Modulus of given two values is:"+(a


%b));

break;

default:

System.out.println("Invalid option");

2.Unconditional Control Statements

java supports the following types of unconditional control statements.

1.break:

it is an unconditional control statement which is used to break any


loop control statement or any switch control statement.

2.continue

it is an unconditional control statement which brings the control to


the inner most loop where the loop condition is reevaluated.

Example

import java.io.*;

class Unconi

{
public static void main(String ar[])throws Exception

int n,i=0;

DataInputStream dis=new DataInputStream(System.in);

System.out.println("Enter any n value:");

n=Integer.parseInt(dis.readLine());

System.out.println("Even nos from 1 to given no are:");

while(i<=n)

i++;

if(i%2!=0)

continue;

System.out.println("\t"+i);

System.out.println("Odd nos from 1 to given no are:");

i=0;

while(i<n)

i++;

if(i%2==0)
continue;

System.out.println("\t"+i);

3.goto break

Arrays in java

Array:
An array is nothing but group of data items that belongs to
similar data type stored in continuous memory locations.

An Array can be referred as a single name or common name.


Each and every individual element was obtained by using a number
called index or subscript.

Array index always starts from 0 to size-1

Single Dimensional Arrays

A group of items that belongs to similar data type stored in continuous


memory locations by using only one index is called single dimensional
array.

Declaration:

Syntax:
Datatype arrayname[]=new datatype[size];
Example:
int a[]=new int[3];

Initialization:

Syntax:
Datatype arrayname[]={value-1,value-2,…………………,value=n};

Eg:
int a[]={1,2,3};

Example:

import java.io.*;

class Array

public static void main(String args[])throws IOException

int n,i;

DataInputStream dis=new DataInputStream(System.in);

System.out.println("Enter no of array ele:");

n=Integer.parseInt(dis.readLine());

int a[]=new int[n];

System.out.println("Enter array elements:");

for(i=0;i<n;i++)

{
a[i]=Integer.parseInt(dis.readLine());

System.out.println("Given array elements are:");

for(i=0;i<n;i++)

System.out.print("\t"+a[i]);

System.out.println("elements of array b are:");

int b[]={1,2,3,4,5,6,7,8,9,10};

for(i=0;i<10;i++)

System.out.print("\t"+b[i]);

2.Two Dimensional Arrays

a group of data items that belongs to similar data type stored in


continuous memory locations using two or more indexes is called two
dimensional array.

Declaration:

Syntax:
Data type Array name[][]=new int[row-size][column-size];

Initialization

Data type Array name[3][3]={1,2,3,4,5,6,7,8,9};

Example:

import java.io.*;

class Array1

public static void main(String ar[])throws Exception

int r,c,i,j;

DataInputStream dis=new DataInputStream(System.in);

System.out.println("Enter no of rows:");

r=Integer.parseInt(dis.readLine());

System.out.println("Enter no of columns:");

c=Integer.parseInt(dis.readLine());

int a[][]=new int[r][c];

System.out.println("Enter array elements:");

for(i=0;i<r;i++)

for(j=0;j<c;j++)
{

a[i][j]=Integer.parseInt(dis.readLine());

System.out.println("Enter array elements:");

for(i=0;i<r;i++)

for(j=0;j<c;j++)

System.out.print("\t"+a[i][j]);

System.out.println();

You might also like

pFad - Phonifier reborn

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

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


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy