literals - selenium4testingselenium4testing.com/wp-content/uploads/core-java-pr…  · web...

56
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, byte…etc 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

Upload: halien

Post on 31-Jan-2018

224 views

Category:

Documents


2 download

TRANSCRIPT

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 & ObjectEncapsulationInheritancePolymorphismData 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 OOPObject 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.0width of MatchBox 1 is 10.0height of MatchBox 1 is 10.0depth of MatchBox 1 is 10.0weight 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 calledCar number: 10No of Tyres: 5accessories: trueBrand: XNumber 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.0width of MatchBox 1 is 10.0height of MatchBox 1 is 10.0depth of MatchBox 1 is 10.0weight 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 StatementsThe 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 StatementThe 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