Introduction: Java is a high-level programming language originally developed by Sun MicroSystems and released in 1995. Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX.
Sun Microsystems has renamed the new J2 versions as Java SE, Java EE and Java ME respectively. Java is guaranteed to be Write Once, Run Anywhere.
Java is:
- Object Oriented: In Java, everything is an Object. Java can be easily extended since it is based on the Object model.
- Platform independent: Unlike many other programming languages including C and C++, when Java is compiled, it is not compiled into platform specific machine, rather into platform independent byte code. This byte code is distributed over the web and interpreted by virtual Machine (JVM) on whichever platform it is being run.
- Simple:Java is designed to be easy to learn. If you understand the basic concept of OOP Java would be easy to master.
- Secure: With Java's secure feature it enables to develop virus-free, tamper-free systems. Authentication techniques are based on public-key encryption.
- Architectural-neutral :Java compiler generates an architecture-neutral object file format which makes the compiled code to be executable on many processors, with the presence of Java runtime system.
- Portable:Being architectural-neutral and having no implementation dependent aspects of the specification makes Java portable. Compiler in Java is written in ANSI C with a clean portability boundary which is a POSIX subset.
- Robust:Java makes an effort to eliminate error prone situations by emphasizing mainly on compile time error checking and runtime checking.
- Multithreaded: With Java's multithreaded feature it is possible to write programs that can do many tasks simultaneously. This design feature allows developers to construct smoothly running interactive applications.
- Interpreted:Java byte code is translated on the fly to native machine instructions and is not stored anywhere. The development process is more rapid and analytical since the linking is an incremental and light weight process.
- High Performance: With the use of Just-In-Time compilers, Java enables high performance.
- Distributed:Java is designed for the distributed environment of the internet.
- Dynamic: Java is considered to be more dynamic than C or C++ since it is designed to adapt to an evolving environment. Java programs can carry extensive amount of run-time information that can be used to verify and resolve accesses to objects on run-time.
History of Java:
James Gosling initiated the Java language project in June 1991 for use in one of his many set-top box projects. The language, initially called Oak after an oak tree that stood outside Gosling's office, also went by the name Green and ended up later being renamed as Java, from a list of random words.
Sun released the first public implementation as Java 1.0 in 1995. It promised Write Once, Run Anywhere (WORA), providing no-cost run-times on popular platforms.
On 13 November 2006, Sun released much of Java as free and open source software under the terms of the GNU General Public License (GPL).
On 8 May 2007, Sun finished the process, making all of Java's core code free and open-source, aside from a small portion of code to which Sun did not hold the copyright.
- In OOP language everything is considered in the form of classes and objects.
- Object - Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behaviors -wagging, barking, eating. An object is an instance of a class.
- Class - A class can be defined as a template/ blue print that describes the behaviors/states that object of its type support.
- Methods - A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed.
- Instance Variables - Each object has its unique set of instance variables. An object's state is created by the values assigned to these instance variables.
- Where to download Java
- How to install Java
- Variables needs to set.
- Writing First Java Application.
- How to compile Java application
- How to Run Java Application
- Difference between terms in Java(JDK vs JRE or J2SE vs J2EE..)
How to Download Java
Latest version of Java can be downloaded from Java Website.
Java Installation
Once downloaded Java can be installed like any other software on Windows.
Setting Environment Variable
After installing Java there are some environment variable that needs to be set.
- CLASSPATH : This environment variable should be declared in system variable. This env variable points the location of JDK home directory. It can also contains the address to folder from which you want jars to get loaded by class loader(For more details of ClassLoader visit here)
- JAVA_HOME : This env variable will point to the location of Java home directory.
How to set environment(env) variable in different platform
Windows XP
To set env variable in windows XP right click “My Computer” icon and select properties. From property windows
Windows Vista / 7
To set env variable in windows Vista / 7 right click “Computer” and select properties. From property windows select “ADVANCED SYSTEM SETTINGS”. In System Properties window select “ADVANCE” tab and then click “ENVIORNMENT VARIABLES”. In next window enter enviornment variable under user/system variables settings.
How to Check if Java is Installed
To check if Java is installed properly open COMMAND prompt in windows OS. To open command prompt write “cmd” in run command and hit enter. In command prompt window write “java -version“. If Java is installed properly and all environment variables are configured correctly it will show version of Installed version. Information should be like
If there is any problem while installing or in setting environment variable output could be like
How to check if java is up to date
To know if Java installed on your system is up to date or not Click Here.
Writing First Java Program
Here we will learn to write first Java program.
If everything till now is configured properly then we can start writing first application. Open any editor or notepad and Write below code.
Once finished edition save the file with name “FirstProgram.java“. Note name of the file should be same as given as it is public class(For more details regarding class file rules click here). Once file saved open the command prompt and change directory where file is saved with cd command. And fire “JAVAC” command which is used to compile the java code as below.
As java file is compiled properly compiler must have created a class file for the java source file in same location or other depending on package declaration. As there is no package declaration in given code so .class file will be create in same folder as java file.
How to Run Java Application
As java file is compiled with “javac” command. We can now run the application. To run above program. Fire “JAVA” command as given below.
1
2
3
4
|
C:JBT>java FirstProgramme
Hello world!
C:JBT>
|
When you compile a java source file we get a .class file, consisting byte code.
Because of this byte code java is platform independent
About Java programs, it is very important to keep in mind the following points.
- Case Sensitivity - Java is case sensitive, which means identifier Hello and hello would have different meaning in Java.
- Class Names - For all class names the first letter should be in Upper Case.
If several words are used to form a name of the class, each inner word's first letter should be in Upper Case.
Example class MyFirstJavaClass - Method Names - All method names should start with a Lower Case letter.
If several words are used to form the name of the method, then each inner word's first letter should be in Upper Case.
Example public void myMethodName() - Program File Name - Name of the program file should exactly match the class name.
When saving the file, you should save it using the class name (Remember Java is case sensitive) and append '.java' to the end of the name (if the file name and the class name do not match your program will not compile).
Example : Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as'MyFirstJavaProgram.java' - public static void main(String args[]) - Java program processing starts from the main() method which is a mandatory part of every Java program..
Java Identifiers:
All Java components require names. Names used for classes, variables and methods are called identifiers.
In Java, there are several points to remember about identifiers. They are as follows:
- All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an underscore (_).
- After the first character identifiers can have any combination of characters.
- A key word cannot be used as an identifier.
- Most importantly identifiers are case sensitive.
- Examples of legal identifiers: age, $salary, _value, __1_value
- Examples of illegal identifiers: 123abc, -salary
Java Modifiers:
Like other languages, it is possible to modify classes, methods, etc., by using modifiers. There are two categories of modifiers:
- Access Modifiers: default, public , protected, private
- Non-access Modifiers: final, abstract, strictfp
We will be looking into more details about modifiers in the next section.
Java Variables:
We would see following type of variables in Java:
- Local Variables
- Class Variables (Static Variables)
- Instance Variables (Non-static variables)
Java Keywords:
The following list shows the reserved words in Java. These reserved words may not be used as constant or variable or any other identifier names.
abstract | assert | boolean | break |
byte | case | catch | char |
class | const | continue | default |
do | double | else | enum |
extends | final | finally | float |
for | goto | if | implements |
import | instanceof | int | interface |
long | native | new | package |
private | protected | public | return |
short | static | strictfp | super |
switch | synchronized | this | throw |
throws | transient | try | void |
volatile | while |
Comments in Java
Java supports single-line and multi-line comments very similar to c and c++. All characters available inside any comment are ignored by Java compiler.
/* This is my first java program.
* This will print 'Hello World' as the output
* This is an example of multi-line comments.
*/
public static void main(String []args){
// This is an example of single line comment
/* This is also an example of single line comment. */
System.out.println("Hello World");
}
}
Using Blank Lines:
A line containing only whitespace, possibly with a comment, is known as a blank line, and Java totally ignores it.
Inheritance:
In Java, classes can be derived from classes. Basically if you need to create a new class and here is already a class that has some of the code you require, then it is possible to derive your new class from the already existing code.
This concept allows you to reuse the fields and methods of the existing class without having to rewrite the code in a new class. In this scenario the existing class is called the superclass and the derived class is called the subclass.
Interfaces:
In Java language, an interface can be defined as a contract between objects on how to communicate with each other. Interfaces play a vital role when it comes to the concept of inheritance.
An interface defines the methods, a deriving class(subclass) should use. But the implementation of the methods is totally up to the subclass.
Java is an Object-Oriented Language. As a language that has the Object Oriented feature, Java supports the following fundamental concepts:
- Polymorphism
- Inheritance
- Encapsulation
- Abstraction
- Classes
- Objects
- Instance
- Method
- Message Parsing
In this chapter, we will look into the concepts Classes and Objects.
- Object - Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behaviors -wagging, barking, eating. An object is an instance of a class.
- Class - A class can be defined as a template/blue print that describes the behaviors/states that object of its type support.
Classes in Java:
A class is a blue print from which individual objects are created.
A sample of a class is given below:
public class Dog{
String breed;
int age;
String color;
void barking(){
}
void hungry(){
}
void sleeping(){
}
}
A class can contain any of the following variable types.
- Local variables: Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed.
- Instance variables: Instance variables are variables within a class but outside any method. These variables are instantiated when the class is loaded. Instance variables can be accessed from inside any method, constructor or blocks of that particular class.
- Class variables: Class variables are variables declared with in a class, outside any method, with the static keyword.
A class can have any number of methods to access the value of various kinds of methods. In the above example, barking(), hungry() and sleeping() are methods.
Constructors:
When discussing about classes, one of the most important sub topic would be constructors. Every class has a constructor. If we do not explicitly write a constructor for a class the Java compiler builds a default constructor for that class.
Each time a new object is created, at least one constructor will be invoked. The main rule of constructors is that they should have the same name as the class. A class can have more than one constructor.
Example of a constructor is given below:
public class Puppy{
public Puppy(){
}
public Puppy(String name){
// This constructor has one parameter, name.
}
}
Java also supports Singleton Classes where you would be able to create only one instance of a class.
Creating an Object:
As mentioned previously, a class provides the blueprints for objects. So basically an object is created from a class. In Java, the new key word is used to create new objects.
There are three steps when creating an object from a class:
- Declaration: A variable declaration with a variable name with an object type.
- Instantiation: The 'new' key word is used to create the object.
- Initialization: The 'new' keyword is followed by a call to a constructor. This call initializes the new object.
Example of creating an object is given below:
public class Puppy{
public Puppy(String name){
// This constructor has one parameter, name.
System.out.println("Passed Name is :" + name );
}
public static void main(String []args){
// Following statement would create an object myPuppy
Puppy myPuppy = new Puppy( "tommy" );
}
}
If we compile and run the above program, then it would produce the following result:
Passed Name is :tommy
Accessing Instance Variables and Methods:
Instance variables and methods are accessed via created objects. To access an instance variable the fully qualified path should be as follows:
/* First create an object */
ObjectReference = new Constructor();
/* Now call a variable as follows */
ObjectReference.variableName;
/* Now you can call a class method as follows */
ObjectReference.MethodName();
Example:
This example explains how to access instance variables and methods of a class:
public class Puppy{int puppyAge;
public Puppy(String name){
// This constructor has one parameter, name.
System.out.println("Passed Name is :" + name );
}
public void setAge( int age ){
puppyAge = age;
}
public int getAge( ){
System.out.println("Puppy's age is :" + puppyAge );
return puppyAge;
}
public static void main(String []args){
/* Object creation */
Puppy myPuppy = new Puppy( "tommy" );
/* Call class method to set puppy's age */
myPuppy.setAge( 2 );
/* Call another class method to get puppy's age */
myPuppy.getAge( );
/* You can access instance variable as follows as well */
System.out.println("Variable Value :" + myPuppy.puppyAge );
}
}
If we compile and run the above program, then it would produce the following result:
Passed Name is :tommy
Puppy's age is :2
Variable Value :2
Source file declaration rules:
As the last part of this section let's now look into the source file declaration rules. These rules are essential when declaring classes, import statements and package statements in a source file.
- There can be only one public class per source file.
- A source file can have multiple non public classes.
- The public class name should be the name of the source file as well which should be appended by .java at the end. For example : The class name is . public class Employee{} Then the source file should be as Employee.java.
- If the class is defined inside a package, then the package statement should be the first statement in the source file.
- If import statements are present then they must be written between the package statement and the class declaration. If there are no package statements then the import statement should be the first line in the source file.
- Import and package statements will imply to all the classes present in the source file. It is not possible to declare different import and/or package statements to different classes in the source file.
Classes have several access levels and there are different types of classes; abstract classes, final classes, etc. I will be explaining about all these in the access modifiers chapter.
Apart from the above mentioned types of classes, Java also has some special classes called Inner classes and Anonymous classes.
Java Package:
In simple, it is a way of categorizing the classes and interfaces. When developing applications in Java, hundreds of classes and interfaces will be written, therefore categorizing these classes is a must as well as makes life much easier.
Import statements:
In Java if a fully qualified name, which includes the package and the class name, is given then the compiler can easily locate the source code or classes. Import statement is a way of giving the proper location for the compiler to find that particular class.
For example, the following line would ask compiler to load all the classes available in directory java_installation/java/io :
import java.io.*;
Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory.Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals, or characters in these variables.There are two data types available in Java:
- Primitive Data Types
- Reference/Object Data Types
There are three kinds of variables in Java:
- Local variables
- Instance variables
- Class/static variables
Local variables:
- Local variables are declared in methods, constructors, or blocks.
- Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor or block.
- Access modifiers cannot be used for local variables.
- Local variables are visible only within the declared method, constructor or block.
- Local variables are implemented at stack level internally.
- There is no default value for local variables so local variables should be declared and an initial value should be assigned before the first use.
Example:
Here, age is a local variable. This is defined inside pupAge() method and its scope is limited to this method only.
public class Test{
public void pupAge(){
int age = 0;
age = age + 7;
System.out.println("Puppy age is : " + age);
}
public static void main(String args[]){
Test test = new Test();
test.pupAge();
}
}
This would produce the following result:
Puppy age is: 7
Example:
Following example uses age without initializing it, so it would give an error at the time of compilation.
public class Test{
public void pupAge(){
int age;
age = age + 7;
System.out.println("Puppy age is : " + age);
}
public static void main(String args[]){
Test test = new Test();
test.pupAge();
}
}
This would produce the following error while compiling it:
Test.java:4:variable number might not have been initialized
age = age + 7;
^
1 error
Instance variables:
- Instance variables are declared in a class, but outside a method, constructor or any block.
- When a space is allocated for an object in the heap, a slot for each instance variable value is created.
- Instance variables are created when an object is created with the use of the keyword 'new' and destroyed when the object is destroyed.
- Instance variables hold values that must be referenced by more than one method, constructor or block, or essential parts of an object's state that must be present throughout the class.
- Instance variables can be declared in class level before or after use.
- Access modifiers can be given for instance variables.
- The instance variables are visible for all methods, constructors and block in the class. Normally, it is recommended to make these variables private (access level). However visibility for subclasses can be given for these variables with the use of access modifiers.
- Instance variables have default values. For numbers the default value is 0, for Booleans it is false and for object references it is null. Values can be assigned during the declaration or within the constructor.
- Instance variables can be accessed directly by calling the variable name inside the class. However within static methods and different class ( when instance variables are given accessibility) should be called using the fully qualified name . ObjectReference.VariableName.
Example:
import java.io.*;
public class Employee{
// this instance variable is visible for any child class.
public String name;
// salary variable is visible in Employee class only.
private double salary;
// The name variable is assigned in the constructor.
public Employee (String empName){
name = empName;
}
// The salary variable is assigned a value.
public void setSalary(double empSal){
salary = empSal;
}
// This method prints the employee details.
public void printEmp(){
System.out.println("name : " + name );
System.out.println("salary :" + salary);
}
public static void main(String args[]){
Employee empOne = new Employee("Ransika");
empOne.setSalary(1000);
empOne.printEmp();
}
}
This would produce the following result:
name : Ransika
salary :1000.0
Class/static variables:
- Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block.
- There would only be one copy of each class variable per class, regardless of how many objects are created from it.
- Static variables are rarely used other than being declared as constants. Constants are variables that are declared as public/private, final and static. Constant variables never change from their initial value.
- Static variables are stored in static memory. It is rare to use static variables other than declared final and used as either public or private constants.
- Static variables are created when the program starts and destroyed when the program stops.
- Visibility is similar to instance variables. However, most static variables are declared public since they must be available for users of the class.
- Default values are same as instance variables. For numbers, the default value is 0; for Booleans, it is false; and for object references, it is null. Values can be assigned during the declaration or within the constructor. Additionally values can be assigned in special static initializer blocks.
- Static variables can be accessed by calling with the class name . ClassName.VariableName.
- When declaring class variables as public static final, then variables names (constants) are all in upper case. If the static variables are not public and final the naming syntax is the same as instance and local variables.
Example:
import java.io.*;
public class Employee{
// salary variable is a private static variable
private static double salary;
// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";
public static void main(String args[]){
salary = 1000;
System.out.println(DEPARTMENT+"average salary:"+salary);
}
}
This would produce the following result:
Development average salary:1000
here may be a situation when we need to execute a block of code several number of times, and is often referred to as a loop.Java has very flexible three looping mechanisms. You can use one of the following three loops:
- while Loop
- do...while Loop
- for Loop
As of Java 5, the enhanced for loop was introduced. This is mainly used for Arrays.
The while Loop:
A while loop is a control structure that allows you to repeat a task a certain number of times.
Syntax:
The syntax of a while loop is:
while(Boolean_expression)
{
//Statements
}
When executing, if the boolean_expression result is true, then the actions inside the loop will be executed. This will continue as long as the expression result is true.
Here, key point of the while loop is that the loop might not ever run. When the expression is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed.
Example:
public class Test {
public static void main(String args[]) {
int x = 10;
while( x < 20 ) {
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}
}
}
This would produce the following result:
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
The do...while Loop:
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time.
Syntax:
The syntax of a do...while loop is:
do
{
//Statements
}while(Boolean_expression);
Notice that the Boolean expression appears at the end of the loop, so the statements in the loop execute once before the Boolean is tested.
If the Boolean expression is true, the flow of control jumps back up to do, and the statements in the loop execute again. This process repeats until the Boolean expression is false.
Example:
public class Test {
public static void main(String args[]){
int x = 10;
do{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 20 );
}
}
This would produce the following result:
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
The for Loop:
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.
A for loop is useful when you know how many times a task is to be repeated.
Syntax:
The syntax of a for loop is:
for(initialization; Boolean_expression; update)
{
//Statements
}
Here is the flow of control in a for loop:
- The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
- Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement past the for loop.
- After the body of the for loop executes, the flow of control jumps back up to the update statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the Boolean expression.
- The Boolean expression is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then update step, then Boolean expression). After the Boolean expression is false, the for loop terminates.
Example:
public class Test {
public static void main(String args[]) {
for(int x = 10; x < 20; x = x+1) {
System.out.print("value of x : " + x );
System.out.print("\n");
}
}
}
This would produce the following result:
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
Enhanced for loop in Java:
As of Java 5, the enhanced for loop was introduced. This is mainly used for Arrays.
Syntax:
The syntax of enhanced for loop is:
for(declaration : expression)
{
//Statements
}
- Declaration: The newly declared block variable, which is of a type compatible with the elements of the array you are accessing. The variable will be available within the for block and its value would be the same as the current array element.
- Expression: This evaluates to the array you need to loop through. The expression can be an array variable or method call that returns an array.
Example:
public class Test {
public static void main(String args[]){
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ){
System.out.print( x );
System.out.print(",");
}
System.out.print("\n");
String [] names ={"James", "Larry", "Tom", "Lacy"};
for( String name : names ) {
System.out.print( name );
System.out.print(",");
}
}
}
This would produce the following result:
10,20,30,40,50,
James,Larry,Tom,Lacy,
The break Keyword:
The break keyword is used to stop the entire loop. The break keyword must be used inside any loop or a switch statement.
The break keyword will stop the execution of the innermost loop and start executing the next line of code after the block.
Syntax:
The syntax of a break is a single statement inside any loop:
break;
Example:
public class Test {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
if( x == 30 ) {
break;
}
System.out.print( x );
System.out.print("\n");
}
}
}
This would produce the following result:
10
20
The continue Keyword:
The continue keyword can be used in any of the loop control structures. It causes the loop to immediately jump to the next iteration of the loop.
- In a for loop, the continue keyword causes flow of control to immediately jump to the update statement.
- In a while loop or do/while loop, flow of control immediately jumps to the Boolean expression.
Syntax:
The syntax of a continue is a single statement inside any loop:
continue;
Example:
public class Test {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
if( x == 30 ) {
continue;
}
System.out.print( x );
System.out.print("\n");
}
}
}
This would produce the following result:
10
20
40
50
There are two types of decision making statements in Java. They are:
- if statements
- switch statements
The if Statement:
An if statement consists of a Boolean expression followed by one or more statements.
Syntax:
The syntax of an if statement is:
if(Boolean_expression)
{
//Statements will execute if the Boolean expression is true
}
If the Boolean expression evaluates to true then the block of code inside the if statement will be executed. If not the first set of code after the end of the if statement (after the closing curly brace) will be executed.
Example:
public class Test {
public static void main(String args[]){
int x = 10;
if( x < 20 ){
System.out.print("This is if statement");
}
}
}
This would produce the following result:
This is if statement
The if...else Statement:
An if statement can be followed by an optional else statement, which executes when the Boolean expression is false.
Syntax:
The syntax of an if...else is:
if(Boolean_expression){
//Executes when the Boolean expression is true
}else{
//Executes when the Boolean expression is false
}
Example:
public class Test {
public static void main(String args[]){
int x = 30;
if( x < 20 ){
System.out.print("This is if statement");
}else{
System.out.print("This is else statement");
}
}
}
This would produce the following result:
This is else statement
The if...else if...else Statement:
An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement.
When using if , else if , else statements there are few points to keep in mind.
- An if can have zero or one else's and it must come after any else if's.
- An if can have zero to many else if's and they must come before the else.
- Once an else if succeeds, none of the remaining else if's or else's will be tested.
Syntax:
The syntax of an if...else is:
if(Boolean_expression 1){
//Executes when the Boolean expression 1 is true
}else if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true
}else if(Boolean_expression 3){
//Executes when the Boolean expression 3 is true
}else {
//Executes when the none of the above condition is true.
}
Example:
public class Test {
public static void main(String args[]){
int x = 30;
if( x == 10 ){
System.out.print("Value of X is 10");
}else if( x == 20 ){
System.out.print("Value of X is 20");
}else if( x == 30 ){
System.out.print("Value of X is 30");
}else{
System.out.print("This is else statement");
}
}
}
This would produce the following result:
Value of X is 30
Nested if...else Statement:
It is always legal to nest if-else statements which means you can use one if or else if statement inside another if or else if statement.
Syntax:
The syntax for a nested if...else is as follows:
if(Boolean_expression 1){
//Executes when the Boolean expression 1 is true
if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true
}
}
You can nest else if...else in the similar way as we have nested if statement.
Example:
public class Test {
public static void main(String args[]){
int x = 30;
int y = 10;
if( x == 30 ){
if( y == 10 ){
System.out.print("X = 30 and Y = 10");
}
}
}
}
This would produce the following result:
X = 30 and Y = 10
The switch Statement:
A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case.
Syntax:
The syntax of enhanced for loop is:
switch(expression){
case value :
//Statements
break; //optional
case value :
//Statements
break; //optional
//You can have any number of case statements.
default : //Optional
//Statements
}
The following rules apply to a switch statement:
- The variable used in a switch statement can only be a byte, short, int, or char.
- You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.
- The value for a case must be the same data type as the variable in the switch and it must be a constant or a literal.
- When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.
- When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.
- Not every case needs to contain a break. If no break appears, the flow of control will fall throughto subsequent cases until a break is reached.
- A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.
Example:
public class Test {
public static void main(String args[]){
//char grade = args[0].charAt(0);
char grade = 'C';
switch(grade)
{
case 'A' :
System.out.println("Excellent!");
break;
case 'B' :
case 'C' :
System.out.println("Well done");
break;
case 'D' :
System.out.println("You passed");
case 'F' :
System.out.println("Better try again");
break;
default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}
}
Compile and run above program using various command line arguments. This would produce the following result:
$ java Test
Well done
Your grade is a C
$
Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects.The Java platform provides the String class to create and manipulate strings.Creating Strings:
The most direct way to create a string is to write:String greeting = "Hello world!";
Whenever it encounters a string literal in your code, the compiler creates a String object with its value in this case, "Hello world!'.As with any other object, you can create String objects by using the new keyword and a constructor. The String class has eleven constructors that allow you to provide the initial value of the string using different sources, such as an array of characters.public class StringDemo{ public static void main(String args[]){ char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.'}; String helloString = new String(helloArray); System.out.println( helloString ); } }
This would produce the following result:hello.
Note: The String class is immutable, so that once it is created a String object cannot be changed. If there is a necessity to make a lot of modifications to Strings of characters, then you should use String Buffer & String Builder Classes.String Length:
Methods used to obtain information about an object are known as accessor methods. One accessor method that you can use with strings is the length() method, which returns the number of characters contained in the string object.After the following two lines of code have been executed, len equals 17:public class StringDemo { public static void main(String args[]) { String palindrome = "Dot saw I was Tod"; int len = palindrome.length(); System.out.println( "String Length is : " + len ); } }
This would produce the following result:String Length is : 17
Concatenating Strings:
The String class includes a method for concatenating two strings:string1.concat(string2);
This returns a new string that is string1 with string2 added to it at the end. You can also use the concat() method with string literals, as in:"My name is ".concat("Zara");
Strings are more commonly concatenated with the + operator, as in:"Hello," + " world" + "!"
which results in:"Hello, world!"
Let us look at the following example:public class StringDemo { public static void main(String args[]) { String string1 = "saw I was "; System.out.println("Dot " + string1 + "Tod"); } }
This would produce the following result:Dot saw I was Tod
No comments:
Post a Comment