You are on page 1of 41

Java Programming

Java Programming language is developed by James Gosling at Sun Microsystems.


It was developed in 1995 for developing programs for electronic devices for interactive
television
Java programs are platform independent
On every system JVM(Java Virtual Machine) will take care of running java programs ( write once
Run Anywhere)
Java is developed based on the Features of C, C++.
Java is Object Oriented Programming language.

OOPs Concepts
Class & Object
Encapsulation
Inheritance
Polymorphism
Data abstraction

Data Types :
Specifies the type of data stored in the system.
int, char, string, Boolean, double, float, byteetc

Java Primitive Data Types and Wrapper Classes

In programming languages a data type is an attribute of a piece of data that explains what kind of
data is being dealt with. This involves setting constraints on the data, such as what values that
data can take on, and what operations may be performed on that data. The Java programming
language is strongly-typed, which means that all variables must first be defined or declared
before they can be used in the actual code. This is often related to the Option Explicit statement
used within Microsoft languages.

Primitive Data Types

byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of
-128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving
memory in large arrays, where the memory savings actually matters. They can also be used in
place of int where their limits help to clarify your code; the fact that a variable's range is limited
can serve as a form of documentation.

short: The short data type is a 16-bit signed two's complement integer. It has a minimum value
of -32,768 and a maximum value of 32,767 (inclusive). As with byte, the same guidelines apply:
you can use a short to save memory in large arrays, in situations where the memory savings
actually matters.
int: The int data type is a 32-bit signed two's complement integer. It has a minimum value of
-2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). For integral values, this data
type is generally the default choice unless there is a reason (like the above) to choose something
else. This data type will most likely be large enough for the numbers your program will use, but
if you need a wider range of values, use long instead.

long: The long data type is a 64-bit signed two's complement integer. It has a minimum value of
-9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive).
Use this data type when you need a range of values wider than those provided by int.

float: The float data type is a single-precision 32-bit IEEE 754 floating point. Its range of values
is beyond the scope of this discussion, but is specified in section 4.2.3 of the Java Language
Specification. As with the recommendations for byte and short, use a float (instead of double) if
you need to save memory in large arrays of floating point numbers. This data type should never
be used for precise values, such as currency. For that, you will need to use the java.math.
BigDecimal class instead. Numbers and Strings covers BigDecimal and other useful classes
provided by the Java platform.

double: The double data type is a double-precision 64-bit IEEE 754 floating point. Its range of
values is beyond the scope of this discussion, but is specified in section 4.2.3 of the Java
Language Specification. For decimal values, this data type is generally the default choice. As
mentioned above, this data type should never be used for precise values, such as currency.

boolean: The boolean data type has only two possible values: true and false. Use this data type
for simple flags that track true/false conditions. This data type represents one bit of information,
but its "size" isn't something that's precisely defined.

char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000'
(or 0) and a maximum value of '\uffff' (or 65,535 inclusive).

Wrapper Classes for Primitive Data Types


Primitive data types are not classes in Java. Therefore they do not come with instance variables
and methods. This is good for efficiency, but seems to force us in a non-object oriented direction.
To accommodate this, there are wrapper classes.
Literals
You may have noticed that the new keyword isn't used when initializing a variable of a primitive
type. Primitive types are special data types built into the language; they are not objects created
from a class. A literal is the source code representation of a fixed value; literals are represented
directly in your code without requiring computation. (Sun Microsystems, 1995-2007)

Variables :
Variables are identifiers to store the value in the memory, the variables are available only
during runtime of the program.
Declare variables
int x,y;
char x(10);
boolean y;
variable declaration is compulsory
To declare a variable in Java, all that is needed is the data type followed by the variable name:

int numberOfDays;
In the above example, a variable called "numberOfDays" has been declared with a data type of
int. Notice how the line ends with a semi-colon. The semi-colon tells the Java compiler that the
declaration is complete.

Now that it has been declared, numberOfDays can only ever hold values that match the
definition of the data type (i.e., for an int data type the value can only be a whole number
between -2,147,483,648 to 2,147,483,647).

Declaring variables for other data types is exactly the same:

byte nextInStream;
short hour;
long totalNumberOfStars;
float reactionTime;
double itemPrice;

Initializing Variables
Before a variable can be used it must be given an initial value. This is called initializing the
variable. If we try to use a variable without first giving it a value:

int numberOfDays;
//try and add 10 to the value of numberOfDays
numberOfDays = numberOfDays + 10;

the compiler will throw an error:

variable numberOfDays might not have been initialized


To initialize a variable we use an assignment statement. An assignment statement follows the
same pattern as an equation in mathematics (e.g., 2 + 2 = 4). There is a left side of the equation, a
right side and an equals sign (i.e., "=") in the middle. To give a variable a value, the left side is
the name of the variable and the right side is the value:

int numberOfDays;
numberOfDays = 7;
In the above example, numberOfDays has been declared with a data type of int and has been
giving an initial value of 7. We can now add ten to the value of numberOfDays because it has
been initialized:

int numberOfDays;
numberOfDays = 7;
numberOfDays = numberOfDays + 10;
System.out.println(numberOfDays);
Typically, the initializing of a variable is done at the same time as its declaration:

//declare the variable and give it a value all in one statement


int numberOfDays = 7;
Choosing Variable Names
The name given to a variable is known as an identifier. As the term suggests, the way the
compiler knows which variables it's dealing with is through the variable's name.

There are certain rules for identifiers:

reserved words cannot be used.

they cannot start with a digit but digits can be used after the first character (e.g., name1,
n2ame are valid).

they can start with a letter, an underscore (i.e., "_") or a dollar sign (i.e., "$").

you cannot use other symbols or spaces (e.g., "%","^","&","#").

Always give your variables meaningful identifiers. If a variable holds the price of a book, then
call it something like "bookPrice". If each variable has a name that makes it clear what it's being
used for, it will make finding errors in your programs a lot easier.

Finally, there are naming conventions in Java that I would encourage you to use. You may have
noticed that all the examples I have given follow a certain pattern. When more than one word is
used in combination in a variable name it is given a capital letter (e.g., reactionTime,
numberOfDays.) This is known as mixed case and is the preferred choice for variable identifiers.

Class :
What is Java Class?
Java class is nothing but a template for object you are going to create or its a blue print by using
this we create an object. In simple word we can say its a specification or a pattern which we
define and every object we define will follow that pattern.

What does Java Class Consist


When we create class in java the first step is keyword class and then name of the class or
identifier we can say.
Next is class body which starts with curly braces {} and between this all things related with that
class means their property and method will come here.

Template is:
Class (name of the class)
{

(Here define member of class)

Access level of class:

Java class has mainly two type of access level:


Default: class objects are accessible only inside the package.
Public: class objects are accessible in code in any package.

What are members of Class?


When we create a class its totally incomplete without defining any member of this class same
like we can understand one family is incomplete if they have no members.

Field: field is nothing but the property of the class or object which we are going to create .for
example if we are creating a class called computer then they have property like model,
mem_size, hd_size, os_type etc

Method: method is nothing but the operation that an object can perform it define the behavior of
object how an object can interact with outside world .startMethod (), shutdownMethod ().

Access Level of members: Access level is nothing but where we can use that members of the
class.
Each field and method has an access level:
private: accessible only in this class
package or default: accessible only in this package
protected: accessible only in this package and in all subclasses of this class
public: accessible everywhere this class is available

Real world example of Class in Java Programming:

In real world if we want to understand about the class everything of same quality can be
visualize as a class e.g. men,women,birds ,bicycles ,cars or we can say vehicle .
The entire vehicle will make one class they have the property like no_of_wheels, color, model,
brand etc.now we can think changeGear () and speedOfvehicle (), applyBreak () etc as a method
on that class. Similarly all human being also can be one class now their member will be a men
,women ,child.,isAlive() ,isDeath() can be their method or behavior of that class .again we can
make Men or women a separate class and define their property and method accordingly,
In short in java every problem we get solution can be think in terms of class and object.

One Java class example:


Class Stock
{
Public commodity;
Public price;
Public void buy (int no_of commodity)
{

}
Public boolean sale ()
{

}
}

In this example Stock is called Class and commodity, price are field and buy() and sale() are two
methods defined inside class. To access elements of Class you need to create an instance of class
Stock. You can create instance of Class using keyword new as shown below

Stock highBetaStock = new Stock();

For calling method of Stock just call by using instance.

highBetaStock.buy(1000);
highBetaStock.sell();

Summary:

In short in java everything must be thinking in terms of java class its nothing but a template they
have their own members and methods for accessing those members. The entire member has their
own visibility which is decided by the developer where they want to use those objects.

A class will have set of properties and methods and these are the building blocks in java
programming
Ex: TV----properties : color, name, price, model, methods : on, off, volume, brigtness
Window -------properties : height, width, bgcolor, forground color, title methods :
close, minimize, maximize, activate, dragetc

Ex:
public class Emp
{
string ename="james";
int sal=2000;
string dob="10-10-1980";
public void getdetails()
{
System.out.println("Emp name :"+ename);
System.out.println("Salary :"+sal);
System.out.println("DOB :"+dob);
}
public static void main(String args[])
{
Emp e=new Emp();
e.getdetails();
}
}

System.out.println------ to print the output


main is the starting point of the program

Access specifiers :
Public ------- the scope is we can access the methods in any class
Private--------we can access these methods only in this class
Protected------we can access these methods in this class and inherited class

import java.io.*;

public class Emp


{
String ename;
int sal;
String dob;

public void getdetails()


{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
try
{
System.out.println("Enter Employee name");
ename=br.readLine();
System.out.println("Enter Employee sal");
sal=Integer.parseInt(br.readLine());
System.out.println("Enter Employee DOB");
dob=br.readLine();
}
catch(Exception ex){
}
System.out.println("Emp name :"+ename);
System.out.println("Salary :"+sal);
System.out.println("DOB :"+dob);
}
public static void main(String args[])
{
Emp e=new Emp();
e.getdetails();
}
}

Escape sequence characters

\b backspace
\t Tab
\n linefeed
\f formfeed
\r carriage return
\" double quote, "
\' single quote, '
\\ backslash, \

OOPS Concepts

Brief Introduction to OOP


Object Oriented Programming or OOP is the technique to create programs based on the real
world. Unlike procedural programming, here in the OOP programming model programs are
organized around objects and data rather than actions and logic. Objects represent some concepts
or things and like any other objects in the real Objects in programming language have certain
behavior, properties, type, and identity. In OOP based language the principal aim is to find out
the objects to manipulate and their relation between each other. OOP offers greater flexibility and
compatibility and is popular in developing larger application. Another important work in OOP is
to classify objects into different types according to their properties and behavior. So OOP based
software application development includes the analysis of the problem, preparing a solution,
coding and finally its maintenance.
Inheritance - This is the mechanism of organizing and structuring software program. Though
objects are distinguished from each other by some additional features but there are objects that
share certain things common. In object oriented programming classes can inherit some common
behavior and state from others. Inheritance in OOP allows to define a general class and later to
organize some other classes simply adding some details with the old class definition. This saves
work as the special class inherits all the properties of the old general class and as a programmer
you only require the new features. This helps in a better data analysis, accurate coding and
reduces development time.

Abstraction - The process of abstraction in Java is used to hide certain details and only show the
essential features of the object. In other words, it deals with the outside view of an object
(interface).

Encapsulation - This is an important programming concept that assists in separating an object's


state from its behavior. This helps in hiding an object's data describing its state from any further
modification by external component. In Java there are four different terms used for hiding data
constructs and these are public, private, protected and package. As we know an object can
associated with data with predefined classes and in any application an object can know about the
data it needs to know about. So any unnecessary data are not required by an object can be hidden
by this process. It can also be termed as information hiding that prohibits outsiders in seeing the
inside of an object in which abstraction is implemented.

Polymorphism - It describes the ability of the object in belonging to different types with specific
behavior of each type. So by using this, one object can be treated like another and in this way it
can create and define multiple level of interface. Here the programmers need not have to know
the exact type of object in advance and this is being implemented at runtime.

Inheritance

Java Inheritance defines an is-a relationship between a superclass and its subclasses. This means
that an object of a subclass can be used wherever an object of the superclass can be used. Class
Inheritance in java mechanism is used to build new classes from existing classes. The
inheritance relationship is transitive: if class x extends class y, then a class z, which extends class
x, will also inherit from class y.

For example a car class can inherit some properties from a General vehicle class. Here we find
that the base class is the vehicle class and the subclass is the more specific car class. A subclass
must use the extends clause to derive from a super class which must be written in the header of
the subclass definition. The subclass inherits members of the superclass and hence promotes
code reuse. The subclass itself can add its own new behavior and properties. The
java.lang.Object class is always at the top of any Class inheritance hierarchy.

class Box
{
double width;
double height;
double depth;
Box() {
}
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
void getVolume() {
System.out.println("Volume is : " + width * height * depth);
}
}

public class MatchBox extends Box {

double weight;
MatchBox() {
}
MatchBox(double w, double h, double d, double m) {
super(w, h, d);
weight = m;
}
public static void main(String args[]) {
MatchBox mb1 = new MatchBox(10, 10, 10, 10);
mb1.getVolume();
System.out.println("width of MatchBox 1 is " + mb1.width);
System.out.println("height of MatchBox 1 is " + mb1.height);
System.out.println("depth of MatchBox 1 is " + mb1.depth);
System.out.println("weight of MatchBox 1 is " + mb1.weight);
}
}
Output

Volume is : 1000.0
width of MatchBox 1 is 10.0
height of MatchBox 1 is 10.0
depth of MatchBox 1 is 10.0
weight of MatchBox 1 is 10.0

What is not possible using java class Inheritance?

1. Private members of the superclass are not inherited by the subclass and can only be indirectly
accessed.
2. Members that have default accessibility in the superclass are also not inherited by subclasses
in other packages, as these members are only accessible by their simple names in subclasses
within the same package as the superclass.
3. Since constructors and initializer blocks are not members of a class, they are not inherited by a
subclass.
4. A subclass can extend only one superclass
class Vehicle {

// Instance fields
int noOfTyres; // no of tyres
private boolean accessories; // check if accessorees present or not
protected String brand; // Brand of the car
// Static fields
private static int counter; // No of Vehicle objects created
// Constructor
Vehicle() {
System.out.println("Constructor of the Super class called");
noOfTyres = 5;
accessories = true;
brand = "X";
counter++;
}
// Instance methods
public void switchOn() {
accessories = true;
}
public void switchOff() {
accessories = false;
}
public boolean isPresent() {
return accessories;
}
private void getBrand() {
System.out.println("Vehicle Brand: " + brand);
}
// Static methods
public static void getNoOfVehicles() {
System.out.println("Number of Vehicles: " + counter);
}
}

class Car extends Vehicle {

private int carNo = 10;


public void printCarInfo() {
System.out.println("Car number: " + carNo);
System.out.println("No of Tyres: " + noOfTyres); // Inherited.
// System.out.println("accessories: " + accessories); // Not Inherited.
System.out.println("accessories: " + isPresent()); // Inherited.
// System.out.println("Brand: " + getBrand()); // Not Inherited.
System.out.println("Brand: " + brand); // Inherited.
// System.out.println("Counter: " + counter); // Not Inherited.
getNoOfVehicles(); // Inherited.
}
}

public class VehicleDetails { // (3)

public static void main(String[] args) {


new Car().printCarInfo();
}
}

Output

Constructor of the Super class called


Car number: 10
No of Tyres: 5
accessories: true
Brand: X
Number of Vehicles: 1

this and super keywords


The two keywords, this and super to help you explicitly name the field or method that you want.
Using this and super you have full control on whether to call a method or field present in the
same class or to call from the immediate superclass. This keyword is used as a reference to the
current object which is an instance of the current class. The keyword super also references the
current object, but as an instance of the current classs super class.

The this reference to the current object is useful in situations where a local variable hides, or
shadows, a field with the same name. If a method needs to pass the current object to another
method, it can do so using the this reference. Note that the this reference cannot be used in a
static context, as static code is not executed in the context of any object.

class Counter {

int i = 0;
Counter increment() {
i++;
return this;
}
void print() {
System.out.println("i = " + i);
}
}
public class CounterDemo extends Counter {

public static void main(String[] args) {


Counter x = new Counter();
x.increment().increment().increment().print();
}
}
Output

Volume is : 1000.0
width of MatchBox 1 is 10.0
height of MatchBox 1 is 10.0
depth of MatchBox 1 is 10.0
weight of MatchBox 1 is 10.0

Polymorphism

What is Polymorphism?

Polymorphism is THE concept to master if you want to master object-oriented programming.


Because Java is an object-oriented language, it makes sense that you should learn the concepts
and power of polymorphism in Java.
Simply put, polymorphism is what allows actions to act differently based on the object
performing the action or the object the action is being performed on. Let's just use a super
simple, real life example. What is a typical sound that a cat makes? Let's just say it's meow. Let's
call this action makeSound() because remember, a method can represent an action. What sound
does a dog make? Let's just say a dog goes woof. We can also call this action makeSound(). Let's
also just pretend that all animals can makeSound(). Thus, makeSound(), depending on the type of
animal, does something different. The action acts differently based on the object.

This concept of polymorphism in Java especially, is actually not hard to understand at all. Oh
look, different animals make different sounds, and the same method can be used to make each
distinct sound. If you've done the Java inheritance tutorial, you already know how to do this!

One powerful tool for using polymorphic behavior is to use the same method name but in the
same class, over and over again to get the desired effects you want. How can we use
polymorphism in Java to accomplish this?

Overloaded Methods

Let's use our makeSound() example again. Let's say a dog makes a woof sound, but if the dog is
injured, the dog might make a whimper noise instead. How can we use makeSound() to produce
both sounds? Take a look at this code snippet:

NOTE: At this point, if you're not sure you understand the code you see, you REALLY should
go back to the Intermediate Tutorials and read the tutorial on Methods In Java. Then you can
come back to learn about polymorphism in Java once you have a better understanding of
methods.
We can see here that depending on the number of parameters we pass to makeSound(), the dog
will make a different sound. But wait! Couldn't we have just used an if statement and make this
just one method? Yes, we could have done that and that's probably a better way of programming
this for this particular example. What if an outside action causes the difference in dog sound
though? Something like this:

If the dog did not have the variable to know it was hurt, you would not be able to write that if
statement as easily.
You can overload a method as much as you want as long as the number of parameters are
different or the types of parameters are different. You could not do this for example:
This is because those are the same number of parameters AND are the same types of parameters.

Overridden Methods

In Java, you can create a method in a superclass (or parent class), then in a subclass ALSO define
that method. Let's see an example of this using Animal:

Now, let's say you could actually create Animals. If you could, then calling makeSound() would
call the method defined in the superclass. If you create a specific Dog, calling makeSound() will
display woof. Now let's say you created a specific Cat. In that example, Cat does not have a
makeSound() method, so when you call makeSound() on Cat, it calls the method in the
superclass Animal and does nothing. Remember, Cat and Dog are subclasses of Animal because
they extend Animal.
This behavior is called method overriding, and it is EXTREMELY powerful stuff when it comes
to polymorphism in Java. Java will let you do this because its possible more specific types of
objects have more specific behaviors for actions. How does Java then know which method to
actually call? Java will always pick the object's true type for choosing which method to call, the
superclass or the subclass. We will see what true type really means in the next section.
Dynamic Method Binding

Do not let the long name confuse you. This is not that scary of a term! We won't discuss why this
is dynamic, but let's just say that Java decides what method to call during runtime, or once the
program is running. Dynamic method binding is how Java decides what method to call when it
has to decide between the superclass and the subclass. So, how exactly does it decide? To
illustrate this point, we must first illustrate the concept of true type versus referenced type.

Look, we just made a Dog but declared it as an Animal! Normally you would see this:

However, you can also declare a variable by its supertype or abstract type to make it more
generic. Let's say you don't know what kind of animal you want:

Notice how the variable is not assigned to anything! We have an animal that has not been
instantiate, and it does not equal anything. We can't create just Animals because they are abstract,
so we must make a specific kind of animal, which is what we did with the example above by
making the Animal be a new Dog.
So, which version of makeSound() would you use if you saw Animal animal = new Dog() ?
Would you choose the Animal's version or the Dog's version? The answer is that Java will choose
the true type, and the true type is the object that actually gets created. In this example, what we
are really creating is a Dog, even though we are referencing the variable as an Animal.

Why in the world wouldn't we just do Dog dog = new Dog() ? The answer is that by using
abstraction, you can actually group many different types of objects together. Let's see how we
can use this concept for storing objects:
We could not do the above if the Cat objects and Dog objects were made the traditional way and
not by referencing them as Animals.
It is very important you do not flip the reference and the true type! You could not do this:

First of all, in our example, you cannot create Animal objects because they are abstract. Let's
assume you could though. This is still illegal because a specific type cannot be the reference of a
more broad type. Think about it this way: A dog is an animal but an animal is not necessarily a
dog. The above example is basically saying that an Animal is a Dog, and this is not always true.
Polymorphism in Java allows you to fully control how you group objects together and gives you
the power to make them as specific as you want. It is also the crucial part of object-oriented
programming that allows you to build hierarchies of objects, objects that have a logical structure
that makes sense in the real world. Because of polymorphism, you can create highly
sophisticated programs in Java that are easy to read and are well organized. It does not guarantee
an awesome organization of your code, but if you're careful it can help you immensely in doing
so.

Conditional Statments
The if-then and if-then-else Statements
The if Statement
The if statement is basic conditional statement of all control flow statements. If the condition
matches only the specified statements are executed. That is if the condition is true.

For example, the Emp class could allow to increase salary if he is permanent emp

class Emp
{
public void Salarycal()
{
if(empstatus= = permanent)
{
//code to cal salary
}
}

If this test evaluates to false (meaning that the emp is not permanent emp), control jumps to the
end of the if statement.

Deciding when to omit the braces is a matter of personal taste. Omitting them can make the code
more brittle. If a second statement is later added to the "then" clause, a common mistake would
be forgetting to add the newly required braces. The compiler cannot catch this sort of error; you'll
just get the wrong results.

The if-else Statement


The if-else statement provides a secondary path of execution when an "if" clause evaluates to
false. You can use an if-else statement in the salarycal method to take some if emp is permanent
emp or else contract emp.

class Emp
{
public void Salarycal()
{
if(empstatus= = permanent)
{
//code to cal salary
}
else
{
// code to cal salary for not permanent emp
}
}

The following program, Sample, assigns a grade based on the value of a test score: an A for a
score of 90% or above, a B for a score of 80% or above, and so on.

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

int score = 72;


char grade;
if (score >= 90) {
grade = 'A';
} else if (score >= 80) {
grade = 'B';
} else if (score >= 70) {
grade = 'C';
} else if (score >= 60) {
grade = 'D';
} else {
grade = 'F';
}
System.out.println("Grade = " + grade);
}
}
The output from the program is:

Grade = C
You may have noticed that the value of score can satisfy more than one expression in the
compound statement: 72 >= 70 and 72 >= 60. However, once a condition is satisfied, the
appropriate statements are executed (grade = 'C';) and the remaining conditions are not
evaluated.

Examples :

Display the given number is even or odd

class Example1
{
public static void main(String args[])
{
int n=5;
if(n % 2 = = 0)
{
system.out.println("It is even number");
}
else
{
system.out.println("It is odd number");
}
}
}
Display the biggest of 2 numbers
class Example2
{
public static void main(String args[])
{
int x=5;
int y=8;

if(x > y)
{
system.out.println("x is biggest");
}
else
{
system.out.println("y is biggest");
}
}
}

Switch Case Statement

The Switch case statement can be used sometimes as an alternative to multiple if else
conditions
The switch statement can have a number of possible execution paths. A switch works with the
byte, short, char, and int primitive data types. It also works with enumerated types (discussed in
Enum Types), the String class, and a few special classes that wrap certain primitive types:
Character, Byte, Short, and Integer (discussed in Numbers and Strings).

Ex: The below class check the char is vowel or not

class Volcheck
{
char str;
str='a';
Switch (str)
{
case 'a'
case 'e'
case 'i'
case 'o'
case 'u'
system.out.println("It is vowel");
break;
default:
system.out.println("It is not vowel");
}

public class DispMonth


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

int month = 8;
String strmonth;
switch (month)
{
case 1: strmonth = "January";
break;
case 2: strmonth = "February";
break;
case 3: strmonth = "March";
break;
case 4: strmonth = "April";
break;
case 5: strmonth = "May";
break;
case 6: strmonth = "June";
break;
case 7: strmonth = "July";
break;
case 8: strmonth = "August";
break;
case 9: strmonth = "September";
break;
case 10: strmonth = "October";
break;
case 11: strmonth = "November";
break;
case 12: strmonth = "December";
break;
default: strmonth = "Invalid month";
break;
}
System.out.println(strmonth);
}
}

Loop Statements
The Loop statements are used to run the statements for multiple Iterations
Different Loop statements in java
while
do while
for..loop
The while statement continually executes group of statements while a particular condition is true.
Its syntax can be expressed as:

while (condition)
{
statement(s)
}
The while statement evaluates condition, which returns a Boolean value. If the condition
evaluates to true, the while statement executes the statement(s) in the while block

Example : Display numbers from 1 to 10

class Sample
{
public static void main(String args[])
{
int i;
i=1;
while(i<=10)
{
system.out.println("The value is "+i);
i=i+1;
}
}

dowhile
The do loop also executes the program while the condition is statisfied but like while,,
here the block of statements are executed and then check the condition

class Sample
{
public static void main(String args[])
{
int i;
i=1;
do
{
system.out.println("The value is "+i);
i=i+1;
}while(i<=10);
}

Difference between while and do..while


class Sample
{
public static void main(String args[])
{
int i;
i=12;
while(i<=10)
{
system.out.println("The value is "+i);
i=i+1;
}
}
In the above code, first check the condition and execute the block, as the condition is not
statisfied, the block is not executed,

class Sample
{
public static void main(String args[])
{
int i;
i=12;
do
{
system.out.println("The value is "+i);
i=i+1;
}while(i<=10);
}
In the above code, first execute the block and then check the condition, as the block is executed 1
time then check the condition, as condition not satisfied it will stop, but already one time
executed

for Loop Statement


The for statement provides a way to iterate over a range of values. Programmers often refer to it
as the "for loop" because of the way in which it repeatedly loops until a particular condition is
satisfied. Syntax of for loop is below

for (initialization; termination;increment)


{
statement(s)
}
When using this version of the for statement, keep in mind that:

The initialization expression initializes the loop; it's executed once, as the loop begins.

When the termination expression evaluates to false, the loop terminates.


The increment expression is invoked after each iteration through the loop; it is perfectly
acceptable for this expression to increment or decrement a value.

class Sample
{
public static void main(String args[])
{
for(int i=1;i<=20;i++)
{
system.out.println("The value is "+i);
}
}

''print series of numbers like below


1 1 2 3 5 8 13 21 33...100

public class Example1


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

int a,b,c;
a=1;
b=1;
c=a+b;
system.out.println(a);
system.out.println(b);
while(c<=100)
{
system.out.println(c);
a=b;
b=c;
c=a+b;
}
}
}
Print Sum of Even number from 1 to 100

class Evensum
{
public static void main(String args[])
{
int sum=0;
for(int i=1;i<=100;i++)
{
if(i %2= = 0)
{
sum=sum+i
}
}
System.out.println(Sum of all even numbers from 1-100 is +sum);
}
}

Array
An array is a variable to store multiple values of same data type

Once defined , the size of an array is fixed and cannot increase to accommodate more
elements.

The first element of an array index starts with zero.


For example declared an array like below

Int x[6]

x[0]=0;
x[1]=1;
x[2]=2;
x[3]=3;
x[4]=4;
x[5]=5;

how this helps is that the index (the number in the bracket[]) can be referenced by a
variable for easy looping.

for(count=0; count<5; count++)


{
System.out.println(x[count]);
}

Using and array in your program is a 3 step process -


1) Declaring your Array
2) Constructing your Array
3) Initializing your Array

Syntax for Declaring Array Variables is

<elementType>[] <arrayName>;
or

<elementType> <arrayName>[];

Example:

int intArray[]; // Defines that intArray is an ARRAY variable of which will store integer values
int []intArray;

Constructing an Array

<arrayName> = new <elementType>[<noOfElements>];

Example:
intarr = new int[10]; // Defines that intArray will store 10 integer values

Declaration and Construction combined


int intarr[] = new int[10];

Initializing an Array
intarr[0]=1; // Assigns an integer value 1 to the first element 0 of the array
intarr[1]=2; // Assigns an integer value 2 to the second element 1 of the array

Declaring and Initializing an Array


<elementType>[] <arayName> = {<arrayInitializerCode>};

Example:

int intarr[] = {1, 2, 3, 4}; // Initilializes an integer array of length 4 where the first element is 1 ,
second element is 2 and so on.
Assignment: First Array Program

Example

class ArrayDemo
{
public static void main(String args[])
{
int arr[ ] = new int[7];
for (int count=0;count<7;count++)
{
arr[count]=count+1;
}
for (int count=0;count<7;count++)
{
System.out.println("arr["+count+"] = "+arr[count]);
}
System.out.println("Length of Array = "+arr.length);
}
}

Save , Compile & Run the code. Observe the Output

arrays are passed by reference


Arrays are passed to functions by reference, or as a pointer to the original. This means anything
you do to the Array inside the function affects the original.

Assignment: To understand Array are passed by reference

class ArrayDemo
{
public static void passByReference(String a[]);
{
a[1] = "Changed";
}
public static void main(String args[])
{
String []b={"Apple","Mango","Orange"};
System.out.println("Before Function Call "+b[0]);
ArrayDemo.passByReference(b);
System.out.println("After Function Call "+b[0]);
}
}
Save , Compile & Run the code. Observe the Output

multidimensional arrays
Multidimensional arrays, are arrays of arrays.

To declare a multidimensional array variable, specify each additional index using another set of
square brackets.

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

When you allocate memory for a multidimensional array, you need only specify the memory for
the first (leftmost) dimension.

You can allocate the remaining dimensions separately.

In Java the length of each array in a multidimensional array is under your control.
Ex:
int twoD[][] = new int[4][];

twoD[0] = new int[5];

twoD[1] = new int[6];

twoD[2] = new int[7];

twoD[3] = new int[8];

Package

Creating and Using Packages


To make types easier to find and use, to avoid naming conflicts, and to control access,
programmers bundle groups of related types into packages.

Definition:
A package is a grouping of related types providing access protection and name space
management. Note that types refers to classes, interfaces, enumerations, and annotation types.
Enumerations and annotation types are special kinds of classes and interfaces, respectively, so
types are often referred to in this lesson simply as classes and interfaces.

The types that are part of the Java platform are members of various packages that bundle classes
by function: fundamental classes are in java.lang, classes for reading and writing (input and
output) are in java.io, and so on. You can put your types in packages too.

Suppose you write a group of classes that represent graphic objects, such as circles, rectangles,
lines, and points. You also write an interface, Draggable, that classes implement if they can be
dragged with the mouse.

//in the Draggable.java file


public interface Draggable {
. . .
}

//in the Graphic.java file


public abstract class Graphic {
. . .
}

//in the Circle.java file


public class Circle extends Graphic
implements Draggable {
. . .
}

//in the Rectangle.java file


public class Rectangle extends Graphic
implements Draggable {
. . .
}

//in the Point.java file


public class Point extends Graphic
implements Draggable {
. . .
}

//in the Line.java file


public class Line extends Graphic
implements Draggable {
. . .
}
You should bundle these classes and the interface in a package for several reasons, including the
following:

You and other programmers can easily determine that these types are related.

You and other programmers know where to find types that can provide graphics-related
functions.

The names of your types won't conflict with the type names in other packages because
the package creates a new namespace.

You can allow types within the package to have unrestricted access to one another yet
still restrict access for types outside the package.

Using Package Members


The types that comprise a package are known as the package members.

To use a public package member from outside its package, you must do one of the following:

Refer to the member by its fully qualified name

Import the package member

Import the member's entire package

Each is appropriate for different situations, as explained in the sections that follow.
Referring to a Package Member by Its Qualified Name
So far, most of the examples in this tutorial have referred to types by their simple names, such as
Rectangle and StackOfInts. You can use a package member's simple name if the code you are
writing is in the same package as that member or if that member has been imported.

However, if you are trying to use a member from a different package and that package has not
been imported, you must use the member's fully qualified name, which includes the package
name. Here is the fully qualified name for the Rectangle class declared in the graphics
package in the previous example.

graphics.Rectangle
You could use this qualified name to create an instance of graphics.Rectangle:

graphics.Rectangle myRect = new graphics.Rectangle();


Qualified names are all right for infrequent use. When a name is used repetitively, however,
typing the name repeatedly becomes tedious and the code becomes difficult to read. As an
alternative, you can import the member or its package and then use its simple name.

Importing a Package Member


To import a specific member into the current file, put an import statement at the beginning of
the file before any type definitions but after the package statement, if there is one. Here's how
you would import the Rectangle class from the graphics package created in the previous
section.

import graphics.Rectangle;
Now you can refer to the Rectangle class by its simple name.

Rectangle myRectangle = new Rectangle();


This approach works well if you use just a few members from the graphics package. But if you
use many types from a package, you should import the entire package.

Importing an Entire Package


To import all the types contained in a particular package, use the import statement with the
asterisk (*) wildcard character.

import graphics.*;
Now you can refer to any class or interface in the graphics package by its simple name.

Circle myCircle = new Circle();


Rectangle myRectangle = new Rectangle();
The asterisk in the import statement can be used only to specify all the classes within a package,
as shown here. It cannot be used to match a subset of the classes in a package. For example, the
following does not match all the classes in the graphics package that begin with A.

// does not work


import graphics.A*;
Instead, it generates a compiler error. With the import statement, you generally import only a
single package member or an entire package.

Note:
Another, less common form of import allows you to import the public nested classes of an
enclosing class. For example, if the graphics.Rectangle class contained useful nested classes,
such as Rectangle.DoubleWide and Rectangle.Square, you could import Rectangle and its
nested classes by using the following two statements.

import graphics.Rectangle;
import graphics.Rectangle.*;
Be aware that the second import statement will not import Rectangle.

Another less common form of import, the static import statement, will be discussed at the end of
this section.

For convenience, the Java compiler automatically imports three entire packages for each source
file: (1) the package with no name, (2) the java.lang package, and (3) the current package (the
package for the current file).

Apparent Hierarchies of Packages


At first, packages appear to be hierarchical, but they are not. For example, the Java API includes
a java.awt package, a java.awt.color package, a java.awt.font package, and many others
that begin with java.awt. However, the java.awt.color package, the java.awt.font
package, and other java.awt.xxxx packages are not included in the java.awt package. The
prefix java.awt (the Java Abstract Window Toolkit) is used for a number of related packages to
make the relationship evident, but not to show inclusion.

Importing java.awt.* imports all of the types in the java.awt package, but it does not import
java.awt.color, java.awt.font, or any other java.awt.xxxx packages. If you plan to use the
classes and other types in java.awt.color as well as those in java.awt, you must import both
packages with all their files:

import java.awt.*;
import java.awt.color.*;
Name Ambiguities
If a member in one package shares its name with a member in another package and both
packages are imported, you must refer to each member by its qualified name. For example, the
graphics package defined a class named Rectangle. The java.awt package also contains a
Rectangle class. If both graphics and java.awt have been imported, the following is
ambiguous.

Rectangle rect;
In such a situation, you have to use the member's fully qualified name to indicate exactly which
Rectangle class you want. For example,
graphics.Rectangle rect;
The Static Import Statement
There are situations where you need frequent access to static final fields (constants) and static
methods from one or two classes. Prefixing the name of these classes over and over can result in
cluttered code. The static import statement gives you a way to import the constants and static
methods that you want to use so that you do not need to prefix the name of their class.

The java.lang.Math class defines the PI constant and many static methods, including methods
for calculating sines, cosines, tangents, square roots, maxima, minima, exponents, and many
more. For example,

public static final double PI


= 3.141592653589793;
public static double cos(double a)
{
...
}
Ordinarily, to use these objects from another class, you prefix the class name, as follows.

double r = Math.cos(Math.PI * theta);


You can use the static import statement to import the static members of java.lang.Math so that
you don't need to prefix the class name, Math. The static members of Math can be imported either
individually:

import static java.lang.Math.PI;


or as a group:

import static java.lang.Math.*;


Once they have been imported, the static members can be used without qualification. For
example, the previous code snippet would become:

double r = cos(PI * theta);


Obviously, you can write your own classes that contain constants and static methods that you use
frequently, and then use the static import statement. For example,

import static mypackage.MyConstants.*;

String Methods
Method Summary
char charAt(int index)
Returns the character at the specified index.

int compareTo(Object o)
Compares this String to another Object.

int compareTo(String anotherString)


Compares two strings lexicographically.

int compareToIgnoreCase(String str)


Compares two strings lexicographically, ignoring case differences.

String concat(String str)


Concatenates the specified string to the end of this string.

boolean contentEquals(StringBuffer sb)


Returns true if and only if this String represents the same sequence of characters as the
specified StringBuffer.

static String copyValueOf(char[] data)


Returns a String that represents the character sequence in the array specified.

static String copyValueOf(char[] data, int offset, int count)


Returns a String that represents the character sequence in the array specified.

boolean endsWith(String suffix)


Tests if this string ends with the specified suffix.

boolean equals(Object anObject)


Compares this string to the specified object.

boolean equalsIgnoreCase(String anotherString)


Compares this String to another String, ignoring case considerations.

byte[] getBytes()
Encodes this String into a sequence of bytes using the platform's default charset, storing
the result into a new byte array.

void getBytes(int srcBegin, int srcEnd, byte[] dst, int dstBegin)

Deprecated. This method does not properly convert characters into bytes. As of JDK 1.1,
the preferred way to do this is via the the getBytes() method, which uses the platform's default
charset.
byte[] getBytes(String charsetName)
Encodes this String into a sequence of bytes using the named charset, storing the result
into a new byte array.

void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)


Copies characters from this string into the destination character array.

int hashCode()
Returns a hash code for this string.

int indexOf(int ch)


Returns the index within this string of the first occurrence of the specified character.

int indexOf(int ch, int fromIndex)


Returns the index within this string of the first occurrence of the specified character,
starting the search at the specified index.

int indexOf(String str)


Returns the index within this string of the first occurrence of the specified substring.

int indexOf(String str, int fromIndex)


Returns the index within this string of the first occurrence of the specified substring,
starting at the specified index.

String intern()
Returns a canonical representation for the string object.

int lastIndexOf(int ch)


Returns the index within this string of the last occurrence of the specified character.

int lastIndexOf(int ch, int fromIndex)


Returns the index within this string of the last occurrence of the specified character,
searching backward starting at the specified index.

int lastIndexOf(String str)


Returns the index within this string of the rightmost occurrence of the specified substring.

int lastIndexOf(String str, int fromIndex)


Returns the index within this string of the last occurrence of the specified substring,
searching backward starting at the specified index.

int length()
Returns the length of this string.

boolean matches(String regex)


Tells whether or not this string matches the given regular expression.
boolean regionMatches(boolean ignoreCase, int toffset, String other,
int ooffset, int len)
Tests if two string regions are equal.

boolean regionMatches(int toffset, String other, int ooffset, int len)


Tests if two string regions are equal.

String replace(char oldChar, char newChar)


Returns a new string resulting from replacing all occurrences of oldChar in this string
with newChar.

String replaceAll(String regex, String replacement)


Replaces each substring of this string that matches the given regular expression with the
given replacement.

String replaceFirst(String regex, String replacement)


Replaces the first substring of this string that matches the given regular expression with the
given replacement.

String[] split(String regex)


Splits this string around matches of the given regular expression.

String[] split(String regex, int limit)


Splits this string around matches of the given regular expression.

boolean startsWith(String prefix)


Tests if this string starts with the specified prefix.

boolean startsWith(String prefix, int toffset)


Tests if this string starts with the specified prefix beginning a specified index.

CharSequence subSequence(int beginIndex, int endIndex)


Returns a new character sequence that is a subsequence of this sequence.

String substring(int beginIndex)


Returns a new string that is a substring of this string.

String substring(int beginIndex, int endIndex)


Returns a new string that is a substring of this string.

char[] toCharArray()
Converts this string to a new character array.

String toLowerCase()
Converts all of the characters in this String to lower case using the rules of the default
locale.
String toLowerCase(Locale locale)
Converts all of the characters in this String to lower case using the rules of the given
Locale.

String toString()
This object (which is already a string!) is itself returned.

String toUpperCase()
Converts all of the characters in this String to upper case using the rules of the default
locale.

String toUpperCase(Locale locale)


Converts all of the characters in this String to upper case using the rules of the given
Locale.

String trim()
Returns a copy of the string, with leading and trailing whitespace omitted.

static String valueOf(boolean b)


Returns the string representation of the boolean argument.

static String valueOf(char c)


Returns the string representation of the char argument.

static String valueOf(char[] data)


Returns the string representation of the char array argument.

static String valueOf(char[] data, int offset, int count)


Returns the string representation of a specific subarray of the char array argument.

static String valueOf(double d)


Returns the string representation of the double argument.

static String valueOf(float f)


Returns the string representation of the float argument.

static String valueOf(int i)


Returns the string representation of the int argument.

static String valueOf(long l)


Returns the string representation of the long argument.

static String valueOf(Object obj)


Returns the string representation of the Object argument.

Integer Methods
byte byteValue()
Returns the value of this Integer as a byte.

int compareTo(Integer anotherInteger)


Compares two Integer objects numerically.
int compareTo(Object o)
Compares this Integer object to another object.

static Integer decode(String nm)


Decodes a String into an Integer.

double doubleValue()
Returns the value of this Integer as a double.

boolean equals(Object obj)


Compares this object to the specified object.

float floatValue()
Returns the value of this Integer as a float.

static Integer getInteger(String nm)


Determines the integer value of the system property with the specified name.

static Integer getInteger(String nm, int val)


Determines the integer value of the system property with the specified name.

static Integer getInteger(String nm, Integer val)


Returns the integer value of the system property with the specified name.

int hashCode()
Returns a hash code for this Integer.

int intValue()
Returns the value of this Integer as an int.

long longValue()
Returns the value of this Integer as a long.

static int parseInt(String s)


Parses the string argument as a signed decimal integer.

static int parseInt(String s, int radix)


Parses the string argument as a signed integer in the radix specified by the second
argument.

short shortValue()
Returns the value of this Integer as a short.
static String toBinaryString(int i)
Returns a string representation of the integer argument as an unsigned integer in base 2.

static String toHexString(int i)


Returns a string representation of the integer argument as an unsigned integer in base 16.

static String toOctalString(int i)


Returns a string representation of the integer argument as an unsigned integer in base 8.

String toString()
Returns a String object representing this Integer's value.

static String toString(int i)


Returns a String object representing the specified integer.

static String toString(int i, int radix)


Returns a string representation of the first argument in the radix specified by the second
argument.

static Integer valueOf(String s)


Returns an Integer object holding the value of the specified String.

static Integer valueOf(String s, int radix)


Returns an Integer object holding the value extracted from the specified String when
parsed with the radix given by the second argument.

To Create a new Java Class

File menu-? new class? Enter Class name Emp?Select public static void main method OK

Example below are few java programs

Accept data from user and print

import java.io.*;

public class Emp


{
String ename;
int sal;
String dob;

public void getdetails()


{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
try
{
System.out.println("Enter Employee name");
ename=br.readLine();
System.out.println("Enter Employee sal");
sal=Integer.parseInt(br.readLine());
System.out.println("Enter Employee DOB");
dob=br.readLine();
}
catch(Exception ex){
}
System.out.println("Emp name :"+ename);
System.out.println("Salary :"+sal);
System.out.println("DOB :"+dob);
}
public static void main(String args[])
{
Emp e=new Emp();
e.getdetails();
}
}

import java.io.*;

public class sampleif


{
public static void main (String[] args) throws IOException
{
int x,y;
InputStreamReader ins=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(ins);

System.out.println("Enter a number");
x=Integer.parseInt(br.readLine());
System.out.println("Enter another number");
y=Integer.parseInt(br.readLine());
if (x>y)
{
System.out.println("x is biggest");
}
else
{
System.out.println("y is biggest");
}
}
}
import java.io.*;
public class sample
{
public static void main(String[] args) throws IOException
{
System.out.println("Please enter a grade character: A, B, C, or D:");
char grade;
grade=(char)System.in.read();
System.out.println ("\t Grade \t Mark Range");
if (grade=='A')
{
System.out.println ("\t A \t 80 - 100");
}
else if (grade=='B')
{
System.out.println ("\t B \t 70 - 79");
}
else if (grade=='C')
{
System.out.println ("\t C \t 55 -69");
}else if (grade=='D'){
System.out.println ("\t D \t 45 - 54");
}
else
{
System.out.println ("Wrong character inputted!!!");
}
}
}

You might also like