Core Java

Introduction

History, architecture, Java Class File, Java Runtime Environment, The Java Virtual Machine, The Java API, java platform, java development kit, Lambda Expressions, Methods References, Type Annotations, Method Parameter Reflection, setting the path environment variable, Java Compiler And Interpreter, java programs, main (), public, static, void, string [] args, statements, white space, case sensitivity, identifiers, keywords, comments, braces and code blocks, variables, variable name

Data types

Primitive data types, Object Reference Types, Strings, Auto boxing, operators, Arithmetic operators, assignment operators, increment and decrement operator, relational operator, logical operator, bitwise operator, conditional operator.



History

Object-Oriented

• Although influenced by its predecessors, Java was not designed to be source-code compatible with any other language. This allowed the Java team the freedom to design with a blank slate. The object model in Java is simple and easy to extend, while primitive types, such as integers, are kept as high-performance non-objects.

Robust

• The multiplatform environment of the Web places extraordinary demands on a program, because the program must execute reliably in a variety of systems. Thus, the ability to create robust programs was given a high priority in the design of Java. Memory management can be a difficult, tedious task in traditional programming environments. For example, in C/C++, the programmer will often manually allocate and free all dynamic memory.

Multithreaded

• Java was designed to meet the real-world requirement of creating interactive, networked programs. To accomplish this, Java supports multithreaded programming, which allows you to write programs that do many things simultaneously.

Architecture-Neutral

• A central issue for the Java designers was that of code longevity and portability. At the time of Java’s creation, one of the main problems facing programmers was that no guarantee existed that if you wrote a program today, it would run tomorrow—even on the same machine. Operating system upgrades, processor upgrades, and changes in core system resources can all combine to make a program malfunction. The Java designers made several hard decisions in the Java language and the Java Virtual Machine in an attempt to alter this situation.

Interpreted and High Performance

• As described earlier, Java enables the creation of cross-platform programs by compiling into an intermediate representation called Java bytecode. This code can be executed on any system that implements the Java Virtual Machine.

Distributed

• Java is designed for the distributed environment of the Internet because it handles TCP/IP protocols. In fact, accessing a resource using a URL is not much different from accessing a file. Java also supports Remote Method Invocation (RMI). This feature enables a program to invoke methods across a network.

Dynamic

Java programs carry with them substantial amounts of run-time type information that is used to verify and resolve accesses to objects at run time. This makes it possible to dynamically link code in a safe and expedient manner.


Java Architecture

1. Compilation and interpretation in Java

• Java combines both the approaches of compilation and interpretation. First, java compiler compiles the source code into bytecode.

• At the run time, Java Virtual Machine (JVM) interprets this bytecode and generates machine code which will be directly executed by the machine in which java program runs. So java is both compiled and interpreted language.

2. Java Virtual Machine (JVM)

JVM is a component which provides an environment for running Java programs. JVM interprets the bytecode into machine code which will be executed the machine in which the Java program runs.

3. Why Java is Platform Independent?

• Platform independence is one of the main advantages of Java. In another words, java is portable because the same java program can be executed in multiple platforms without making any changes in the source code.

• You just need to write the java code for one platform and the same program will run in any platforms. But how does Java make this possible?

• As we discussed early, first the Java code is compiled by the Java compiler and generates the bytecode. This bytecode will be stored in class files. Java Virtual Machine (JVM) is unique for each platform.

• Though JVM is unique for each platform, all interpret the same bytecode and convert it into machine code required for its own platform and this machine code will be directly executed by the machine in which java program runs. This makes Java platform independent and portable.

• Let’s make it more clearly with the help of the following diagram. Here the same compiled Java bytecode is interpreted by two different JVMS to make it run in Windows and Linux platforms.

• Class loader loads all the class files required to execute the program. Class loader makes the program secure by separating the namespace for the classes obtained through the network from the classes available locally. Once the bytecode is loaded successfully, then next step is bytecode verification by bytecode verifier.

Byte code verifier

• The bytecode verifier verifies the byte code to see if any security problems are there in the code.

It checks the byte code and ensures the followings.

1. The code follows JVM specifications.

2. There is no unauthorized access to memory.

3. The code does not cause any stack overflows.

4. There are no illegal data conversions in the code such as float to object references.

• Once this code is verified and proven that there is no security issues with the code, JVM will convert the byte code into machine code which will be directly executed by the machine in which the Java program runs.

Just in Time Compiler

• You might have noticed the component “Just in Time” (JIT) compiler in Figure 3. This is a component which helps the program execution to happen faster. How? Let’s see in detail.

• As we discussed earlier when the Java program is executed, the byte code is interpreted by JVM. But this interpretation is a slower process. To overcome this difficulty, JRE include the component JIT compiler. JIT makes the execution faster.

• If the JIT Compiler library exists, when a particular bytecode is executed first time, JIT complier compiles it into native machine code which can be directly executed by the machine in which the Java program runs.

• Once the byte code is recompiled by JIT compiler, the execution time needed will be much lesser. This compilation happens when the byte code is about to be executed and hence the name “Just in Time”.

• Once the bytecode is compiled into that particular machine code, it is cached by the JIT compiler and will be reused for the future needs.

• Hence the main performance improvement by using JIT compiler can be seen when the same code is executed again and again because JIT make use of the machine code which is cached and stored.

Why Java is Secure?

• As you have noticed in the prior session “Java Runtime Environment (JRE) and Java Architecture in Detail”, the byte code is inspected carefully before execution by Java Runtime Environment

(JRE).

• This is mainly done by the “Class loader” and “Byte code verifier”. Hence a high level of security is achieved.

Garbage Collection

• Garbage collection is a process by which Java achieves better memory management. As you know, in object oriented programming, objects communicate to each other by passing messages. (If you are not clear about the concepts of objects, please read the prior chapter before continuing in this session).

• Whenever an object is created, there will be some memory allocated for this object. This memory will remain as allocated until there are some references to this object.

• When there is no reference to this object, Java will assume that this object is not used anymore. When garbage collection process happens, these objects will be destroyed and memory will be reclaimed.

• Garbage collection happens automatically. There is no way that you can force garbage collection to happen. There are two methods “System.gc()” and “Runtime.gc()” through which you can make request for garbage collation.

But calling these methods also will not force garbage collection to happen and you cannot make sure when this garbage collection will happen.


Java Class File

What is class file in Java?

Class file in Java is compiled form of Java source file. When we compile Java program which is written in Java source file ended with .java extension, it produces one more class files depending upon how many classes are declared and defined in that Java source file.

• One Java source file can only contain one public class and its name must match with name of file e.g. HelloWorld.java file can contain a public class whose name should be HelloWorld as shown below :


public class HelloWorld

{ public static void main(String... args)

{

System.out.println("I am inside java class HelloWorld");

}

}

If you compile this Java file by

=> javac HelloWorld.java

It will produce

=> HelloWorld.class

• A class file in Java has .class extension and contains bytecode which is instruction for Java Virtual Machine, which then translates that bytecode into platform specific machine level instruction based upon whether Java program is running on Windows or Linux.

• In fact this combination of class file, bytecode and JVM makes Java achieves platform independence. If anyone asks what byte code in Java is, is it machine instruction? You can answer them that it's just meant for JVM and not for a machine.

• When you run a Java program using java command, we provide the name of the class file which contains the main method in Java.

• JVM first loads that file and executes the main method which is the entry point of Java application. Remember java compiler or javac command is used to create a class file from java source file and java command is used to run Java program stored in a class file.

• Since class file contains bytecode in hex format and format of the class file is well documented any one can temper with class file and break Java security grantees. In order to prevent that every Java class file is verified by Verifier after loading during Byte code verification process and Verifier rejects the class file which violates constraints of Java programming language.

Java Runtime Environment (JRE)

• The Java Runtime Environment (JRE), also known as Java Runtime, is part of the Java Development Kit (JDK), a set of programming tools for developing Java applications.

• The Java Runtime Environment provides the minimum requirements for executing a Java application; it consists of the Java Virtual Machine (JVM), core classes, and supporting files.

• It combines the Java Virtual Machine (JVM), platform core classes and supporting libraries. JRE was originally developed by Sun Microsystems Inc., a wholly-owned subsidiary of Oracle Corporation.

• JRE consists of the following components:

o Deployment technologies, including deployment, Java Web Start and Java Plug-in.

o User interface toolkits, including Abstract Window Toolkit (AWT), Swing, Java 2D, Accessibility, Image I/O, Print Service, Sound, drag and drop (DnD) and input methods. o Integration libraries, including Interface Definition Language (IDL), Java Database Connectivity (JDBC), Java Naming and Directory Interface (JNDI), Remote Method Invocation (RMI), Remote Method Invocation Over Internet Inter-Orb Protocol (RMI-IIOP) and scripting.

o Lang and util base libraries, including lang and util, management, versioning, zip, instrument, reflection, Collections, Concurrency Utilities, Java Archive (JAR), Logging, Preferences API, Ref Objects and Regular Expressions.

o Java Virtual Machine (JVM), including Java HotSpot Client and Server Virtual Machines.

JVM (Java Virtual Machine)

• JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in which java bytecode can be executed.

• JVMs are available for many hardware and software platforms (i.e. JVM is platform dependent).

What is JVM?

It is:

1. A specification where working of Java Virtual Machine is specified. But implementation provider is independent to choose the algorithm. Its implementation has been provided by Sun and other companies.

2. An implementation its implementation is known as JRE (Java Runtime Environment).

3. Runtime Instance Whenever you write java command on the command prompt to run the java class, an instance of JVM is created.

What it does

• The JVM performs following operation:

o Loads code o Verifies code o Executes code

o Provides runtime environment

JVM provides definitions for the:

• Memory area

• Class file format

• Register set

Garbage-collected heap

Fatal error reporting etc


Internal Architecture of JVM

Let's understand the internal architecture of JVM. It contains classloader, memory area, execution engine etc.

1) Classloader

Classloader is a subsystem of JVM that is used to load class files.

2) Class(Method) Area

Class (Method) Area stores per-class structures such as the runtime constant pool, field and method data, the code for methods.

3) Heap

It is the runtime data area in which objects are allocated.

4) Stack

• Java Stack stores frames. It holds local variables and partial results, and plays a part in method invocation and return.

• Each thread has a private JVM stack, created at the same time as thread.

• A new frame is created each time a method is invoked. A frame is destroyed when its method invocation completes.

5) Program Counter Register

PC (program counter) register. It contains the address of the Java virtual machine instruction currently being executed.

6) Native Method Stack

It contains all the native methods used in the application.

7) Execution Engine

It contains:

1) A virtual processor

2) Interpreter: Read bytecode stream then execute the instructions.

3) Just-In-Time (JIT) compiler: It is used to improve the performance. JIT compiles parts of the byte code that have similar functionality at the same time, and hence reduces the amount of time needed for compilation. Here the term? Compiler? Refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU.

Java API

• Java application programming interface (API) is a list of all classes that are part of the Java development kit (JDK).

• It includes all Java packages, classes, and interfaces, along with their methods, fields, and constructors. These prewritten classes provide a tremendous amount of functionality to a programmer.

• If you browse through the list of packages in the API, you will observe that there are packages written for GUI programming, networking programming, managing input and output, database programming, and many more.

• Please browse the complete list of packages and their descriptions to see how they can be used. In order to use a class from Java API, one needs to include an import statement at the start of the program.

• For example, in order to use the Scanner class, which allows a program to accept input from the keyboard, one must include the following import statement: import java.util.Scanner;

The above import statement allows the programmer to use any method listed in the Scanner class.

• Another choice for including the import statement is the wildcard option shown below: import java.util.*;

• This version of the import statement imports all the classes in the API’s java.util package and makes them available to the programmer.

• If you check the API and look at the classes written in the java.util package, you will observe that it includes some of the classes that are used often, such as Arrays, ArrayList, Formatter, Random, and many others.

• Another Java package that has several commonly used classes is the java.lang package. This package includes classes that are fundamental to the design of Java language.

• The java.lang package is automatically imported in a Java program and does not need an explicit import statement. Please note that some of the classes that we use very early in Java programming come from this package.

• Commonly used classes in the java.lang package are: Double, Float, Integer, String, StringBuffer, System, and Math.

Java platform

• Java is a platform for application development. A platform is a loosely defined computer industry buzzword that typically means some combination of hardware and system software that will mostly run all the same software.

• For instance PowerMacs running Mac OS 9.2 would be one platform. DEC Alphas running Windows NT would be another.

• There's another problem with distributing executable programs from web pages. Computer programs are very closely tied to the specific hardware and operating system they run.

• A Windows program will not run on a computer that only runs DOS. A Mac application can't run on a UNIX workstation. VMS code can't be executed on an IBM mainframe, and so on.

• Therefore major commercial applications like Microsoft Word or Netscape have to be written almost independently for all the different platforms they run on.

• Netscape is one of the most cross-platform of major applications, and it still only runs on a minority of platforms.

• Java solves the problem of platform-independence by using byte code. The Java compiler does not produce native executable code for a particular machine like a C compiler would.

• Instead it produces a special format called byte code. Java byte code written in hexadecimal, byte by byte, looks like this:

CA FE BA BE 00 03 00 2D 00 3E 08 00 3B 08 00 01 08 00 20 08

• This looks a lot like machine language, but unlike machine language Java byte code is exactly the same on every platform.

• This byte code fragment means the same thing on a Solaris workstation as it does on a Macintosh PowerBook. Java programs that have been compiled into byte code still need an interpreter to execute them on any given platform.

• The interpreter reads the byte code and translates it into the native language of the host machine on the fly. The most common such interpreter is Sun's program java (with a little j).

• Since the byte code is completely platform independent, only the interpreter and a few native libraries need to be ported to get Java to run on a new computer or operating system. The rest of the runtime environment including the compiler and most of the class libraries are written in Java.

Java Development Kit (JDK)

• The Java Development Kit (JDK) is a software development environment used for developing Java applications and applets. It includes the Java Runtime Environment (JRE), an interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation generator (javadoc) and other tools needed in Java development.

• People new to Java may be confused about whether to use the JRE or the JDK. To run Java applications and applets, simply download the JRE. However, to develop Java applications and applets as well as run them, the JDK is needed.

• Java developers are initially presented with two JDK tools, java and javac. Both are run from the command prompt.

• Java source files are simple text files saved with an extension of .java. After writing and saving Java source code, the javac compiler is invoked to create .class files. Once the .class files are created, the 'java' command can be used to run the java program.

• For developers who wish to work in an integrated development environment (IDE), a JDK bundled with Netbeans can be downloaded from the Oracle website.

• Such IDEs speed up the development process by introducing point-and-click and drag-and-drop features for creating an application.

Java Lambda Expressions

• Lambda expression is a new and important feature of Java which was included in Java SE 8. It provides a clear and concise way to represent one method interface using an expression. It is very useful in collection library. It helps to iterate, filter and extract data from collection.

• The Lambda expression is used to provide the implementation of an interface which has functional interface. It saves a lot of code.

• In case of lambda expression, we don't need to define the method again for providing the implementation. Here, we just write the implementation code.

• Java lambda expression is treated as a function, so compiler does not create .class file.

Functional Interface

 Lambda expression provides implementation of functional interface. An interface which has only one abstract method is called functional interface. Java provides an annotation @FunctionalInterface, which is used to declare an interface as functional interface.

Why use Lambda Expression

1. To provide the implementation of Functional interface.

2. Less coding.

Java Lambda Expression Syntax

(argument-list) -> {body}

• Java lambda expression is consisted of three components.

1) Argument-list: It can be empty or non-empty as well.

2) Arrow-token: It is used to link arguments-list and body of expression.

3) Body: It contains expressions and statements for lambda expression.

• Let's see a scenario. If we don't implement Java lambda expression. Here, we are implementing an interface method without using lambda expression.

Java Method References

• Java provides a new feature called method reference in Java 8. Method reference is used to refer method of functional interface. It is compact and easy form of lambda expression.

• Each time when you are using lambda expression to just referring a method, you can replace your lambda expression with method reference.

Types of Method References

There are following types of method references in java:

1. Reference to a static method.

2. Reference to an instance method.

3. Reference to a constructor.

Reference to a Static Method

• You can refer to static method defined in the class. Following is the syntax and example which describe the process of referring static method in Java.

• Syntax

ContainingClass::staticMethodName

Reference to an Instance Method

• Like static methods, you can refer instance methods also. In the following example, we are describing the process of referring the instance method.

Syntax containingObject::instanceMethodName

Java Type Annotations

• The places in which the annotations can be used has been expanded. As mentioned earlier, annotations were originally allowed only on declarations.

• However, with the advent of JDK 8, annotations can also be specified in most of the cases in which a type is used. This expanded aspect of annotations is called as type annotation.

• For example, you can annotate the return type of a method, the type of this within a method, a cast, array levels, an inherited class, and a throws clause. You can also annotate the generic types, including generic type parameter bounds and generic type arguments.

• Type annotations are important because they enable tools to perform additional checks on code to help prevent the errors.

• Understand that, as a general rule, javac will not perform these checks itself. A separate tool is used for this purpose, although such a tool might operate as a compiler plug-in.

• Following are the examples of type annotations:

@NonNull List<String>

List<@NonNull String> str

Arrays<@NonNegative Integer> sort

@Encrypted File file

@Open Connection connection

void divideInteger(int a, int b) throws @ZeroDivisor ArithmeticException

Method Parameter Reflection

• Java provides a new feature in which you can get the names of formal parameters of any method or constructor.

• The java.lang.reflect package contains all the required classes like Method and Parameter to work with parameter reflection.

Method class

It provides information about single method on a class or interface. The reflected method may be a class method or an instance method.

Method Class methods

Parameter class

Parameter class provides information about method parameters, including its name and modifiers. It also provides an alternate means of obtaining attributes for the parameter.

Setting the path environment variable

How to set path in Java o The path is required to be set for using tools such as javac, java etc.

o If you are saving the java source file inside the jdk/bin directory, path is not required to be set because all the tools will be available in the current directory.

o But if you are having your java file outside the jdk/bin folder, it is necessary to set path of JDK.

o There are 2 ways to set java path:

1. temporary

2. permanent

1. How to set Temporary Path of JDK in Windows o To set the temporary path of JDK, you need to follow following steps:

§ Open command prompt

§ copy the path of jdk/bin directory

§ write in command prompt: set path=copied_path o For Example:


set path=C:\Program Files\Java\jdk1.6.0_23\bin Let's see it in the figure given below:

2. How to set Permanent Path of JDK in Windows o For setting the permanent path of JDK, you need to follow these steps:

1)Go to MyComputer properties

2) click on advanced tab

3) click on environment variables

4) click on new tab of user variables

5) write path in variable name

6) Copy the path of bin folder

7) paste path of bin folder in variable value

8) click on ok button

9) click on ok button

Now your permanent path is set. You can now execute any program of java from any drive.

Java Compiler and Interpreter

The difference between an interpreter and a compiler is given below

Java programs

Fibonacci series


class FibonacciExample1

{ public static void main(String args[])

{ int n1=0,n2=1,n3,i,count=10;

System.out.print(n1+" "+n2);

//printing 0 and 1

for(i=2;i<count;++i)

//loop starts from 2 because 0 and 1 are already printed

{

n3=n1+n2;

System.out.print(" "+n3);

n1=n2;

n2=n3;

}

} }


Input: 10

Output: 0 1 1 2 3 5 8 13 21 34

Prime Number

Public class PrimeExample

{

public static void main(String args[])

{ int I,m=0,flag=0;

Int n=3; //it is the number to be checked

If(n==0||n==1)

{

Sysytem.out.println(n+”is not prime number”);

}

Else{

If(n%1==0){

System.out.println(n+”is not prime number”);

Flag=1;

Break;

}

}if(flag==0){system.out.println(n+”is prime number”);

} } }

Input: 44

Output: not a prime number

Input: 7

Output: prime number


Palindrome number

class PalindromeExample{

public static void main(String args[])

int r,sum=0,temp;

int n=454;temp=n;

while(n>0){

r=n%10; //getting remainder

sum=(sum*10)+r;

n=n/10;

}

If(temp==sum)

{

System.out.println(“palindrome number”);

}

Else

{

System.out.println(“not palindrome”);

}

}

Input: 329

Output: not palindrome number

Input: 12321

Output: palindrome number

Factorial number

Class FactorialExample

{

Public static void main(String args[])

{

Int I,fact=1;

Int number=5; //num to cal fact

For(i=0;i<=mumber;i++)

{

Fact=fact*I;

}

Systen.out.println(“Factorial of ”+number is:”+fact);

}

}

Input: 5

Output: 120

Input: 6

output: 720


Armstrong number

class ArmstrongExample

{

public static void main(String[]args)

{

int c=0,a,temp;

int n=153;//It is the number to check

temp=n;

while(n>0)

{

a=n%10;

n=n/10;

c=c+(a*a*a);

}

if(temp==c)

{System.out.println("armstrong number");

}else

{

System.out.println("Not armstrong number");

}

}

}

Input: 153

output: Armstrong number

Input: 22

output: not Armstrong number


main() Method

A Java program needs to start its execution somewhere. A Java program starts by executing the main-method of some class. You can choose the name of the class to execute, but not the name of the method.

The method must always be called main. Here is how the method declaration looks when located inside the Java class declaration from earlier:

package myjavacode;

public class MyClass

{

public static void main(String[] args)

{

}

}


Output: 720


• The three keywords public, static and void have a special meaning. Don't worry about them right now. Just remember that a main() method declaration needs these three keywords.

• After the three keywords you have the method name. To recap, a method is a set of instructions that can be executed as if they were a single operation. By "calling" (executing) a method you execute all the instructions inside that method.

• After the method name comes first a left parenthesis, and then a list of parameters. Parameters are variables (data / values) we can pass to the method which may be used by the instructions in the method to customize its behavior.

• A main method must always take an array of String objects. You declare an array of String objects like this:

String[] stringArray

• Don't worry about what a String is, or what an array is. That will be explained in later texts. Also, it doesn't matter what name you give the parameter.

• In the main () method example earlier I called the String array parameter args, and in the second example I called it stringArray. You can choose the name freely.

• After the method's parameter list comes first a left curly bracket ({), then some empty space, and then a right curly bracket (}).

• Inside the curly brackets you locate the Java instructions that are to be executed when the main method is executed. This is also referred to as the method body. In the example above there are no instructions to be executed. The method is empty.

Let us insert a single instruction into the main method body. Here is an example of how that could look:

package myjavacode; public class MyClass

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

System.out.println("Hello World, Java Program");

}

}


• Now the main method contains this single Java instruction:

System.out.println("Hello World, Java Program");

Public

• A class, method, constructor, interface, etc. declared public can be accessed from any other class. Therefore, fields, methods, blocks declared inside a public class can be accessed from any class belonging to the Java Universe.

• However, if the public class we are trying to access is in a different package, then the public class still needs to be imported. Because of class inheritance, all public methods and variables of a class are inherited by its subclasses.

• Example

o The following function uses public access control –

public static void main(String[] arguments)

{

// ... }


• The main() method of an application has to be public. Otherwise, it could not be called by a Java interpreter (such as java) to run the class.

Static class in Java

Static classes are basically a way of grouping classes together in Java. Java doesn't allow you to create top-level static classes; only nested (inner) static classes

void

The void keyword denotes that a method does not have a return type. However, even though constructor method can never have a return type, it does not have the void keyword in its declaration.

EXAMPLES:

  • The method displayBookData() does not have a return type as shown by the use of the void keyword. Note that the constructor method Book(String, String, String) does not use the void keyword even though it too does not have a return type.

public class Book

{

private String title;

private String author;

private String publisher;

public Book(String title, String author, String publisher)

{

this.title = title;

this.author = author;

this.publisher = publisher;

}

public void displayBookData()

{

System.out.println("Title: " + title);

System.out.println("Author: " + author);

System.out.println("Publisher: " + publisher);

}

}


String[] args

• Each cell of an array of object references works just like an ordinary object reference variable. In the question, strArray[0] starts out with a reference to one String, then is assigned a reference to another. The previous String is now garbage.

• Here is the familiar signature of the main() method:

public static void main( String[] args )

• The phrase String[] args says that main() has a parameter which is a reference to an array of String references. This array is constructed by the Java system just before main() gets control. The elements of the array refer to Strings that contain text from the command line that starts the program. For example, say that a program is started with this command line:

C:\>java StringDemo stringA stringB string

Types of Java Statement

• Control Statement

• Assignment Statement

• In this section we will discuss about control statements. Click here for additional information on assignment statement.

Control Statements

• Conditional execution

• Looping

• Flow Control Statement

Types of Conditional Execution

• If Statement

• If – Else statement

• If- Else-if statement

• Switch Statement

If Statement

• The if statement in Java encloses a portion of code which is executed only if the applied condition is true. If statements only accept boolean expressionas condition.

• Syntax of If Statement

if (true)

System.out.println("Hello! This will always get printed");


if (Boolean Expression) { Code block to get executed }


If Else Statement

• The if Else statement consists of one if condition and one else statement. It encloses a portion of code which is executed only if the if condition is true, if it is false then the else part of the code will be executed. If else statements take only Boolean expression as valid conditions.

• Syntax of If Else Statement

if (1==2)

System.out.println("Hello! This will not get printed");

else

System.out.println("Hello! This will get printed");


if (Boolean Expression) { Code block to get executed }

else{ code block to get executed when above condition is false }

If Else If Statement

• The if else if statement consists of multiple if conditions and an elsestatement. If the if condition is true then the enclosed code will be executed.

• If the if condition is false then it will check the next if condition. If the next if condition is true then the enclosed code will be executed otherwise the elsepart of the code will be executed. If Else If statements takes only Boolean expressions as valid condition.

if (1==2)

System.out.println("Hello! This will not get printed");

else if(1==1)

System.out.println("This will get executed when Above condition is True")


Types of Looping Statement

for while

while loop

do-while loop


Types of Flow Control Statement

• Return Statement

• Continue Statement

• Break Statement

Whitespace

• Whitespace in Java is used to separate the tokens in a Java source file. Whitespace is required in some places, such as between access modifiers, type names and Identifiers, and is used to improve readability elsewhere.

• Wherever whitespace is required in Java, one or more whitespace characters may be used. Wherever whitespace is optional in Java, zero or more whitespace characters may be used.

• Java whitespace consists of the o space character ' ' (0x20), o the tab character (hex 0x09), o the form feed character (hex 0x0c),

• The line separators characters newline (hex 0x0a) or carriage return (hex 0x0d) characters.

• Line separators are special whitespace characters in that they also terminate line comments, whereas normal whitespace does not.

• Other Unicode space characters, including vertical tab, are not allowed as whitespace in Java.

Case sensitivity

• Case sensitivity enforces capital or lower case in text. For example, suppose you have created three variables called "endLoop", "Endloop", and "EndLoop". Even though these variables are composed of the exact same letters in the same exact order, Java does not consider them equal.

• It will treat them all differently.

• This behavior has its roots in the programming language C and C++, on which Java was based, but not all programming languages enforce case sensitivity. Those that do not include Fortran, COBOL, Pascal and most BASIC languages.

• If you follow these tips when coding in Java you should avoid the most common case sensitive errors:

o Java keywords are always written in lowercase. You can find the full list of keywords in the reserved words list.

o Avoid using variable names that differ only in case. Like the example above, if you had three variables called “endLoop”, “Endloop”, and “EndLoop” it would not take long before you mistype one of their names. Then you might find your code changing the value of the wrong variable by mistake.

o Always make sure the class name in your code and java filename match.

Java identifier o A Java identifier is a name given to a package, class, interface, method, or variable. It allows a programmer to refer to the item from other places in the program.

o To make the most out of the identifiers you choose, make them meaningful and follow the standard Java naming conventions.

o EXAMPLES OF JAVA IDENTIFIERS

String name = "Homer Jay Simpson"; int weight = 300; double height = 6;

System.out.printf("My name is %s, my height is %.0f foot and my weight is %d pounds. D'oh!%n", name, height, weight);

Java Keywords

• Keywords are predefined, reserved words used in Java programming that have special meanings to the compiler. For example: int score;

• Here, int is a keyword. It indicates that the variable score is of integer type (32-bit signed two's complement integer).

• You cannot use keywords like int, for, class etc as variable name (or identifiers) as they are part of the Java programming language syntax. Here's the complete list of all keywords in Java programming.


Java Keywords List

Java Comments

The java comments are statements that are not executed by the compiler and interpreter. The comments can be used to provide information or explanation about the variable, method, class or any statement. It can also be used to hide program code for specific time.


Types of Java Comments

There are 3 types of comments in java.

1.

Types of Java

Comments

There are 3 types of comments in java.

Java Single Line Comment

The single line comment is used to comment only one line.

1.Single Line Comment

2.Multi Line Comment

3. Documentation Comment


Syntax:

//This is single line comment Example:

public class CommentExample1

{ public static void main(String[] args)

{ int i=10;//Here, i is a variable

System.out.println(i); }

}

Java Multi Line Comment

The multi-line comment is used to comment multiple lines of code.

Syntax:

/* This is multi line comment

*/

Example:

public class CommentExample2

{ public static void main(String[] args)

{

/* Let's declare and

print variable in java. */

int i=10;

System.out.println(i);

}

}

Java Documentation Comment

The documentation comment is used to create documentation API. To create documentation API, you need to use javadoc tool.

Syntax:

/** This is documentation comment

*/

Example:

/** The Calculator class provides methods to get addition and sub traction of given 2 numbers.*/

public class Calculator

{

/** The add() method returns addition of given numbers.*/

public static int add(int a, int b){return a+b;}

/** The sub() method returns subtraction of given numbers.*/

public static int sub(int a, int b){return a-b;} }

Block of code in Java allows grouping of two or more statements. We use curly braces { } to denote a block of code in Java. Block of code in Java can be used where ever we use a statement. o Every block of code in Java starts with a open curly brace { and ends with close curly brace }.

o There is no restriction on the number of blocks inside a block and the level of nesting the blocks. i.e. Blocks can be nested and can be included inside other blocks.

o Block of code in Java is commonly used in if, for and while statements.

o All class and method contents are also blocks e.g., the class content or the main method in the examples are blocks.

o It is advised to indent i.e. put tabs or spaces so that the inside blocks are one tab more than the containing block. Indenting the blocks will help in resolving the compilation errors faster and the programs will be easy to read.


For example

• Instance initializer, it is a block of code that will execute each time an instance of the class is created.

class Program

{

{

System.out.println("Instance Intializer");

}

public static void main(String[] args)

{

}

}


class Program

{

System.out.println("Instance Intializer");

public static void main(String[] args)

}


• initializer, it is a block of code that will execute only one time when the class is first loaded.

class Program

{

System.out.pr

intln("Instance Intializer");

public static void main(String[] args)

}

A compound statement, it is just a block of code that will execute when the

method is invoked.

class Program

{

public static void main(String[] args)

{

{

static { }

{

}...

System.out.println("Inside method");

....

}

}

}


Variable

• Variable is a name of memory location. There are three types of variables in java: local, instance and static.

• Variable is name of reserved area allocated in memory. In other words, it is a name of memory location. It is a combination of "vary + able" that means its value can be changed.

Example

int a, b, c; // Declares three ints, a, b, and c.

int a = 10, b = 10; // Example of initialization

byte B = 22; // initializes a byte type variable B.

double pi = 3.14159; // declares and assigns a value of PI.

char a = 'a'; // the char variable a iis initialized with value 'a'

Types of Variable

There are three types of variables in java:

o local variable o instance variable

o static variable

1. Local Variable

A variable which is declared inside the method is called local variable.

2. Instance Variable

A variable which is declared inside the class but outside the method, is called instance variable . It is not declared as static.

3. Static variable

A variable that is declared as static is called static variable. It cannot be local.

variable name

Variables in Java Programming is something that can be changed, such as a characteristic or value. If we consider programming concept then we can say that variable is something which can store a value. It is container for storing a value.Variable name may be given by programmer.

Some Rules of Variable Naming Convention:

1. Variable names are case-sensitive.

2. A variable’s name can be any legal identifier.

3. It can contain Unicode letter, Digits and Two Special Characters such as Underscore and dollar Sign.

4. Length of Variable name can be any number.

5. Its necessary to use Alphabet at the start (however we can use underscore , but do not use it ) 6. Some auto generated variables may contain ‘$‘sign. But try to avoid using Dollar Sign.

7. White space is not permitted.

8. Special Characters are not allowed.

9. Digit at start is not allowed.

10. Subsequent characters may be letters, digits, dollar signs, or underscore characters.

11. Variable name must not be a keyword or reserved word.

Data types

Data types in Java

• There are majorly two types of languages. First one is Statically typed languagewhere each variable and expression type is already known at compile time.Once a variable is declared to be of a certain data type, it cannot hold values of other data types.

• Example: C, C++, Java. Other, Dynamically typed languages: These languages can receive different data types over the time.

• Ruby, Python Java is statically typed and also a strongly typed language because in Java, each type of data (such as integer, character, hexadecimal, packed decimal, and so forth) is predefined as part of the programming language and all constants or variables defined for a given program must be described with one of the data types.

• Java has two categories of data:

o Primitive data (e.g., number, character)

o Object data (programmer created types)

Primitive data

Primitive data are only single values; they have no special capabilities. There are 8 primitive data types

Boolean

 Boolean data type represents only one bit of information either true or false. Values of type Boolean are not converted implicitly or explicitly (with casts) to any other type. But the programmer can easily write conversion code.

// A Java program to demonstrate boolean data type class GeeksforGeeks

{

public static void main(String args[])

{

boolean b = true;

if (b == true)

System.out.println("Hi Geek");

}

}

Byte

 The byte data type is an 8-bit signed two’s complement integer.The byte data type is useful for saving memory in large arrays. o Size: 8-bit

o Value: -128 to 127

Short

The short data type is a 16-bit signed two’s complement integer. Similar to byte, use a short to save memory in large arrays, in situations where the memory savings actually matters.

o Size: 16 bit

o Value: -32,768 to 32,767 (inclusive)

Int

• It is a 32-bit signed two’s complement integer.

o Size: 32 bit

o Value: -231 to 231-1

• Note: In Java SE 8 and later, we can use the int data type to represent an unsigned 32-bit integer, which has value in range [0, 232-1]. Use the Integer class to use int data type as an unsigned integer. long:

• The long data type is a 64-bit two’s complement integer.

o Size: 64 bit

o Value: -263 to 263-1.

• Note: In Java SE 8 and later, you can use the long data type to represent an unsigned 64-bit long, which has a minimum value of 0 and a maximum value of 264-1. The Long class also contains methods like compareUnsigned, divideUnsigned etc to support arithmetic operations for unsigned long.

float

The float data type is a single-precision 32-bit IEEE 754 floating point. Use a float (instead of double) if you need to save memory in large arrays of floating point numbers.

o Size: 32 bits

o Suffix : F/f Example: 9.8f

Object Reference Types

1. Strong references.

2. Soft references.

3. Weak references.

4. Phantom references.


Strong references

• The name of this reference type should by itself give you an idea of the importance of the reference in the opinion of the garbage collector. Any object with an active strong reference to it, will never be garbage collected

Employee emp = new Employee();

• An object to which a reference is created in this way will be eligible for garbage collection only when the reference is to it is pointed to null.

emp=null;

Soft references

• The soft reference class is used to create a soft reference to an existing object that is already referred to by a strong reference. The actual object on the heap that is being referred to is called the referent.

• In order to create a SoftReference to an object, you first need to create a strong reference to that object and then pass that object as a parameter to the constructor of the SoftReference object, as shown in the code below.

Employee emp = new Employee (); //1

SoftReference<Employee> softRef = new SoftReference<employee>(emp);

Weak References

• The garbage collector has no regard for an object that only has a week reference. What that means is that the garbage collector will make it eligible for garbage collection because object only has a week reference pointing to it. Not only is that awesome and useful, but desirable as well in some scenarios.

• You can simply create a weak reference to the object, in the same way that we created a soft reference.

DBConnection emp = new Employee(); //1

WeakReference<DBConnection> weakRef = new

WeakReference<DBConnection>(emp);

Java String

• In java, string is basically an object that represents sequence of char values. An array of characters works same as java string. For example:

1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};

2. String s=new String(ch);

String s="javatpoint";

• Java String class provides a lot of methods to perform operations on string such as compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.

Autoboxing in Java

Converting a primitive data type into an object of the corresponding wrapper class is called autoboxing. For example, converting int to Integer or converting long to Long object.


Simple Example of Autoboxing in java:

class BoxingExample1

{ public static void main(String args[])

{

int a=50;

Integer a2=new Integer(a);//Boxing

Integer a3=5;//Boxing

System.out.println(a2+" "+a3);

}

}

Operators in java

• Operator in java is a symbol that is used to perform operations. For example: +, -, *, / etc.

• There are many types of operators in java which are given below:

Unary Operation

Arithmetic operation

shift operation

Relational operation

Bitwise operation

Logical operation

Ternary Operation

Assignment Operation


Arithmetic operation are used in mathematical expressions in the same way that they are used in algebra. The following table lists the arithmetic operations-

Assume integer variable A holds 10 and variable B holds 20, then

Java’s Selection Statements

 Java supports two selection statements: if and switch. These statements allow you to control the flow of your program’s execution based upon conditions known only during run time. You will be pleasantly surprised by the power and flexibility contained in these two statements.

If

• The if statement is Java’s conditional branch statement. It can be used to route program execution through two different paths. Here is the general form of the if statement:

If (condition) statement1;

else statement2;

• Here, each statement may be a single statement or a compound statement enclosed in curly braces (that is, a block).

• The condition is any expression that returns a Boolean value. The else clause is optional. The if works like this: If the condition is true, then statement1 is executed. Otherwise, statement2 (if it exists) is executed.

• In no case will both statements be executed. For example, consider the following: int a, b;

//...

if(a < b) a = 0;

else

b = 0;

• Here, if a is less than b, then a is set to zero. Otherwise, b is set to zero. In no case are they both set to zero. Most often, the expression used to control the if will involve the relational operators. However, this is not technically necessary. It is possible to control the if using a single boolean variable, as shown in this code fragment:

boolean dataAvailable;

//...

if (dataAvailable)

ProcessData();

else

waitForMoreData();

Nested if

• A nested if is an if statement that is the target of another if or else. Nested ifs are very common in programming.

• When you nest ifs, the main thing to remember is that an else statement always refers to the nearest if statement that is within the same block as the else and that is not already associated with an else. Here is an example:

if(i == 10)

{ if(j < 20) a = b; if(k > 100) c = d; // this if is else

a = c; // associated with this else

}

else a = d; // this else refers to if(i == 10)

• As the comments indicate, the final else is not associated with if (j<20) because it is not in the same block (even though it is the nearest if without an else).

• Rather, the final else is associated with if (i==10). The inner else refers to if (k>100) because it is the closest if within the same block.

The if-else-if Ladder

 A common programming construct that is based upon a sequence of nested ifs is the if-elseif ladder. It looks like this:

if(condition) statement;

else if(condition) statement;

else if(condition) statement;

. . .

else statement;

• The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed.

• If none of the conditions is true, then the final else statement will be executed.

• The final else acts as a default condition; that is, if all other conditional tests fail, then the last else statement is performed.

• If there is no final else and all other conditions are false, then no action will take place.

• Here is a program that uses an if-else-if ladder to determine which season a particular month is in.

// Demonstrate if-else-if statements.

class IfElse

{ public static void main(String args[])

{

int month = 4; // April String season;

if(month == 12 || month == 1 || month == 2) season = "Winter";

else if(month == 3 || month == 4 || month == 5) season = "Spring";

else if(month == 6 || month == 7 || month == 8) season = "Summer";

else if(month == 9 || month == 10 || month == 11) season = "Autumn";

else season = "Bogus Month";

System.out.println("April is in the " + season + ".");

}

}

• Here is the output produced by the program:

April is in the spring.

• You might want to experiment with this program before moving on. As you will find, no matter what value you give month, one and only one assignment statement within the ladder will be executed.

Switch

• The switch statement is Java’s multiway branch statement. It provides an easy way to dispatch execution to different parts of your code based on the value of an expression.

• As such, it often provides a better alternative than a large series of if-else-if statements. Here is the general form of a switch statement:

switch (expression)

{ case value1:

// statement sequence break; case value2:

// statement sequence break;

...

case valueN :

// statement sequence break;

default:

// default statement sequence

}


• The switch statement works like this: The value of the expression is compared with each of the values in the case statements.

• If a match is found, the code sequence following that case statement is executed. If none of the constants matches the value of the expression, then the default statement is executed.

• However, the default statement is optional. If no case matches and no default is present, then no further action is taken.

• The break statement is used inside the switch to terminate a statement sequence. When a break statement is encountered, execution branches to the first line of code that follows the entire switch statement.

• This has the effect of “jumping out” of the switch.

• Here is a simple example that uses a switch statement:

// A simple example of the switch.

class SampleSwitch

{ public static void main(String args[])

{ for(int i=0; i<6; i++) switch(i)

{ case 0:

System.out.println("i is zero."); break;

case 1:

System.out.println("i is one."); break;

case 2:

System.out.println("i is two."); break;

case 3:

System.out.println("i is three."); break;

default:

System.out.println("i is greater than 3.");

}

}

}

The output produced by this program is shown here:

i is zero.

i is one.

i is two.

i is three.

i is greater than 3.

i is greater than 3.

• The break statement is optional. If you omit the break, execution will continue on into the next case.

• It is sometimes desirable to have multiple cases without break statements between them. For example, consider the following program:

//In a switch, break statements are optional.

class MissingBreak

{ public static void main(String args[])

{ for(int i=0; i<12; i++) switch(i)

{

case 0:

case 1:

case 2:

case 3:

case 4:

System.out.println("i is less than 5");

}

}


i is less than 5

i is less than 5

i is less than 5

i is less than 10

i is less than 10

i is less than 10

i is less than 10

i is less than 10

i is 10 or more

i is 10 or more


Nested switch Statements

• You can use a switch as part of the statement sequence of an outer switch. This is called a nested switch.

• Since a switch statement defines its own block, no conflicts arise between the case constants in the inner switch and those in the outer switch. For example, the following fragment is perfectly valid:

switch(count)

{ case 1: switch(target)

{ // nested switch case 0:

System.out.println("target is zero");

break;

case 1: // no conflicts with outer switch

System.out.println("target is one");

break;

} break; case 2: // ...

• Here, the case 1: statement in the inner switch does not conflict with the case 1: statement in the outer switch.

• The count variable is compared only with the list of cases at the outer level. If count is 1, then target is compared with the inner list cases.

• In summary, there are three important features of the switch statement to note:

o The switch differs from the if in that switch can only test for equality, whereas if can evaluate any type of Boolean expression. That is, the switch looks only for a match between the value of the expression and one of its case constants.

o No two case constants in the same switch can have identical values. Of course, a switch statement and an enclosing outer switch can have case constants in common.

o A switch statement is usually more efficient than a set of nested ifs.

Iteration Statements

• Java’s iteration statements are for, while, and do-while. These statements create what we commonly call loops.

• As you probably know, a loop repeatedly executes the same set of instructions until a termination condition is met. As you will see, Java has a loop to fit any programming need.

While

• The while loop is Java’s most fundamental loop statement. It repeats a statement or block while its controlling expression is true. Here is its general form:

while(condition)

{

// body of loop

}

• The condition can be any Boolean expression. The body of the loop will be executed as long as the conditional expression is true.

• When condition becomes false, control passes to the next line of code immediately following the loop. The curly braces are unnecessary if only a single statement is being repeated.

• Here is a while loop that counts down from 10, printing exactly ten lines of "tick":

{ }

tick 10

tick 9

tick 8

tick 7

tick 6

tick 5

tick 4

tick 3

tick 2

tick 1


do-while

• As you just saw, if the conditional expression controlling a while loop is initially false, then the body of the loop will not be executed at all.

• However, sometimes it is desirable to execute the body of a loop at least once, even if the conditional expression is false to begin with.

• In other words, there are times when you would like to test the termination expression at the end of the loop rather than at the beginning.

• Fortunately, Java supplies a loop that does just that: the do-while. The do-while loop always executes its body at least once, because its conditional expression is at the bottom of the loop. Its general form is

do

{

// body of loop

}

while (condition);

• Each iteration of the do-while loop first executes the body of the loop and then evaluates the conditional expression.

• If this expression is true, the loop will repeat. Otherwise, the loop terminates. As with all of Java’s loops, condition must be a Boolean expression.

• Here is a reworked version of the “tick” program that demonstrates the do-while loop. It generates the same output as before.

// Demonstrate the do-while loop.

class DoWhile

{ public static void main(String args[])

{ int n = 10; do

{ System.out.println("tick " + n); n--; }

while(n > 0);

}

}

for

• You were introduced to a simple form of the for loop in Chapter 2. As you will see, it is a powerful and versatile construct.

• Beginning with JDK 5, there are two forms of the for loop. The first is the traditional form that has been in use since the original version of Java. The second is the newer “for-each” form.

• Both types of for loops are discussed here, beginning with the traditional form.

• Here is the general form of the traditional for statement:

for(initialization; condition; iteration)

{

// body

}

• If only one statement is being repeated, there is no need for the curly braces. The for loop operates as follows.

• When the loop first starts, the initialization portion of the loop is executed. Generally, this is an expression that sets the value of the loop control variable, which acts as a counter that controls the loop.

• It is important to understand that the initialization expression is executed only once. Next, condition is evaluated.

• This must be a Boolean expression. It usually tests the loop control variable against a target value. If this expression is true, then the body of the loop is executed.

• If it is false, the loop terminates. Next, the iteration portion of the loop is executed. This is usually an expression that increments or decrements the loop control variable.

• The loop then iterates, first evaluating the conditional expression, then executing the body of the loop, and then executing the iteration expression with each pass.

• This process repeats until the controlling expression is false. Here is a version of the “tick” program that uses a for loop:

// Demonstrate the for loop.

class ForTick

{ public static void main(String args[])

{ int n;

for(n=10; n>0; n--)

System.out.println("tick " + n);

}

}

The For-Each Version of the for Loop

• Beginning with JDK 5, a second form of for was defined that implements a “for-each” style loop.

• As you may know, contemporary language theory has embraced the for-each concept, and it has become a standard feature that programmers have come to expect.

• A for-each style loop is designed to cycle through a collection of objects, such as an array, in strictly sequential fashion, from start to finish.

• Unlike some languages, such as C#, that implement a for-each loop by using the keyword foreach, Java adds the for-each capability by enhancing the for statement.

• The advantage of this approach is that no new keyword is required, and no preexisting code is broken.

• The for-each style of for is also referred to as the enhanced for loop.

• The general form of the for-each version of the for is shown here:

for(type itr-var : collection) statement-block

• Here, type specifies the type and itr-var specifies the name of an iteration variable that will receive the elements from a collection, one at a time, from beginning to end. The collection being cycled through is specified by collection.


Jump Statements

• Java supports three jump statements: break, continue, and return. These statements transfer control to another part of your program

Using break

• In Java, the break statement has three uses. First, as you have seen, it terminates a statement sequence in a switch statement. Second, it can be used to exit a loop. Third, it can be used as a “civilized” form of goto. The last two uses are explained here.

Using break to Exit a Loop

• By using break, you can force immediate termination of a loop, bypassing the conditional expression and any remaining code in the body of the loop.

• When a break statement is encountered inside a loop, the loop is terminated and program control resumes at the next statement following the loop. Here is a simple example:

// Using break to exit a loop.

class BreakLoop

System.out.println("i: " + i);

}

}


i: 0

i: 1

i: 6

i: 7

i: 8

i: 9

Loop complete.

Using continue

• Sometimes it is useful to force an early iteration of a loop. That is, you might want to continue running the loop but stop processing the remainder of the code in its body for this particular iteration.

• This is, in effect, a goto just past the body of the loop, to the loop’s end. The continue statement performs such an action.

• In while and do-while loops, a continue statement causes control to be transferred directly to the conditional expression that controls the loop.

• In a for loop, control goes first to the iteration portion of the for statement and then to the conditional expression.

• For all three loops, any intermediate code is bypassed. Here is an example program that uses continue to cause two numbers to be printed on each line:

// Demonstrate continue. class Continue

{ public static void main(String args[])

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

System.out.print(i + " ");

if (i%2 == 0) continue;

System.out.println("");

}

}

}

This code uses the % operator to check if i is even. If it is, the loop continues without printing a newline. Here is the output from this program:

{ for(int j=0; j<10; j++)

{ if(j > i)

{ System.out.println(); continue outer; }

System.out.print(" " + (i * j));

}

}

System.out.println();

}

}

The continue statement in this example terminates the loop counting j and continues with the next iteration of the loop counting i. Here is the output of this program:

0

0 1

0 2 4

0 3 6 9

0 4 8 12 16

0 5 10 15 20 25

0 6 12 18 24 30 36

0 7 14 21 28 35 42 49

0 8 16 24 32 40 48 56 64

0 9 18 27 36 45 54 63 72 81

return

• The last control statement is return. The return statement is used to explicitly return from a method. That is, it causes program control to transfer back to the caller of the method.

• At any time in a method, the return statement can be used to cause execution to branch back to the caller of the method.

• Thus, the return statement immediately terminates the method in which it is executed. The following example illustrates this point.

• Here, return causes execution to return to the Java run-time system, since it is the run-time system that calls main( ):

// Demonstrate return. class Return

{ public static void main(String args[])

{ boolean t = true;

System.out.println("Before the return."); if(t) return; // return to caller System.out.println("This won't execute."); }

}

The output from this program is shown here:

Before the return.