KEMBAR78
Core Java ! | PDF | Java Virtual Machine | Java (Programming Language)
0% found this document useful (0 votes)
15 views52 pages

Core Java !

Java is a high-level, object-oriented programming language developed by Sun Microsystems in 1995, known for its simplicity, platform independence, and security features. It supports various application types including standalone, web, enterprise, and mobile applications, and utilizes components like JVM, JRE, and JDK for execution and development. Key features include dynamic memory allocation, multi-threading, and a robust set of libraries, making Java widely used across numerous devices and applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views52 pages

Core Java !

Java is a high-level, object-oriented programming language developed by Sun Microsystems in 1995, known for its simplicity, platform independence, and security features. It supports various application types including standalone, web, enterprise, and mobile applications, and utilizes components like JVM, JRE, and JDK for execution and development. Key features include dynamic memory allocation, multi-threading, and a robust set of libraries, making Java widely used across numerous devices and applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

Java History and Features

What is Java?
Java is a programming language and a platform. Java is a high level, robust, object-oriented
and secure programming language. It is a case-sensitive language. Java was developed
by Sun Microsystems (which is now the subsidiary of Oracle) in the year 1995. James
Gosling is known as the father of Java.

History
Founded by: SUN Mc systems (Oracle corporation)
First version: JDK1.0(1996)
Author: James Gosling
Project: Green
Strong Features: Object-oriented, platform Independent, Robust

Features Of Java:
Java language has the following features :

1.Simple:
Java is simple programming language, because,
- Java is very easy to learn, Syntax are easy to understand.
- Java applications will take less memory and less execution time. Java has removed
confusion-oriented features like pointers, multiple inheritance.
- There are no any perquisites to learn java.

2.Object-Oriented:
- Java is an object-oriented programming language because everything is written inside
classes and everything is stored in the form of objects.

3.Platform-independent:
- Java is platform independent programming language because it allows its applications to
compile on one operating system and to execute on another operating system. i.e., Write
Once and Run Anywhere (WORA).
- Java is platform independent because of its bytecode (.class file).

4.Architecture Neutral:
- It means that even if you write and compile a program on one hardware configuration and
try to run on some other hardware configuration still it will execute.
- Eg. Suppose I have one java program which is already running on machine that uses
window operating system then I upgrade it to windows 10, RAM size 2GB to 4GB. Same
java program can be running so no need of any changes into it.

5.Portable:
Java is a portable programming language, because, JAVA is able to run its applications
under all the operating systems and under all the hardware Conditions.

6.Secure:
- Java is very good Secure programming language, because,
- JAVA has provided an implicit component inside JVM in the form of "Security Manager" to
provide implicit security.
- Some list of security features is encryption, decryption, cryptography, SSL, etc. This makes
Java popular for banking applications.

7.Robust:
- It uses strong memory management.
- There is no need of pointer concept to access string, array, file, etc.
- Garbage collection is done automatically so no need to do it manually like other
programming languages.

8.Dynamic:
- if any programming language allows memory allocation for primitive datatypes at runtime
then that programming language is called dynamic programming language.
- Java allows to allocate memory for primitive types at runtime so java is dynamic
programming language.

9.Distributed:
By using java we can create 2 types of applications:
1.Standalone applications.
2.Distributed applications.
1)Standalone Applications: If we design any java application without using client-Server arch
then that java application is called as Standalone application.
2)Distributed Applications: If we design any java application on the basis of client-server arch
then that java application is called as Distributed application.
To prepare Distributed applications, JAVA has provided a separate module that is
"J2EE/JAVAEE".

10.multi-threaded:
Multi-threaded means ability to allow more than one thread to execute application, It follows
parallel execution, it will reduce execution time, it will improve application performance. JAVA
is following Multi Thread Model, JAVA is able to provide very good environment to create and
execute more than one thread at a time, due to this reason, JAVA is Multi threaded
Programming Language.

11.High-Perfirmance:
JAVA is high performance programming language due to its rich set of features like Platform
independent, Arch Nuetral, Portable, Robust, Dynamic,..

Applications of Java:

According to Sun, 3 billion devices run Java. There are many devices where Java is currently
used. Some of them are as follows:

1. Desktop Applications such as acrobat reader, media player, antivirus, etc.


2. Web Applications such as irctc.co.in, javatpoint.com, etc.
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games, etc.

Types of Java Applications


1) Standalone Application

Standalone applications are also known as desktop applications or window-based


applications. These are traditional software that we need to install on every machine.
Examples of standalone application are Media player, antivirus, etc. AWT and Swing are used
in Java for creating standalone applications.
2) Web Application

An application that runs on the server side and creates a dynamic page is called a web
application. Currently servlet, JSP, Struts, Spring, hibernate, etc. technologies are used for
creating web applications in Java.

3) Enterprise Application

An application that is distributed in nature, such as banking applications, etc. is called an


enterprise application. It has advantages like high-level security, load balancing, and
clustering. In Java, EJB is used for creating enterprise applications.

4) Mobile Application

An application which is created for mobile devices is called a mobile application. Currently,
Android and Java ME are used for creating mobile applications.

JVM , JRE and JDK

JVM (Java Virtual Machine):


It doesn't physically exist. It is a specification that provides a runtime environment in
which Java byte code can be executed. JVM is a part of JRE(Java Runtime
Environment).The JVM performs following operation:
- Loads code
- Verifies code
- Executes code
- Provides runtime environment
Description

Classloader-
Whenever we run java program it is first loaded into memory by
Classloader. It is used to load the .class files.

Class Area-
It is known as method area. It will store the information about
method code, method name, fields, etc.
Heap Area-
It is the run time area where objects are stored.

Stack Area-
It is used to store the information about the local variables.

PC Register
It includes address of currently executing instruction.
Once Instruction Execution Completes Automatically PC Register will be incremented to
Hold Address of Next Instruction.

Native Method Stack-


For Every Thread JVM will Create a Separate Native Method Stack.

Native Method interface-


It is an interface that interacts with the Native Method Libraries and provides the native
libraries(C, C++) required for the execution.

Execution Engine-
It contain java compiler and interpreter information.

Java Native Libraries


Java Native Library is the collection of Native methods which are required in java.
Native method is a method declared in java but,implemented in non java programming
languages like C ,C++ etc

JRE:
JRE stands for Java Runtime Environment.
The Java Runtime Environment is a set of software tools which are used for developing Java
applications.
It consists of the Java Virtual Machine (JVM), core classes, and supporting files like rt.jar
files.
It is used to provide the runtime environment.

JDK:
JDK is stands Java Development Kit.It is a software development environment which is used
to develop Java applications .
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. It physically exists.

JDK=JRE+Development Tool

Q.Diff between JDK,JRE,JVM and JIT

Ans:

1.Place---JIT is part of JVM JVM is part of JRE JRE is part of JDK.

2.JDK

-Java Developement Kit.

-It provides Runtime Environment and Developement tools(small progs for


compilation,documentation,preparing jar files,etc).

-It contains Developement tools+JRE.

-Using JDK we can compile and execute new application and also we can modify existing
application.

3.JRE

-Java Runtime Environment.

-It provides only runtime environment it doesnt provide any developement tools.
-It contains JVM

-Hence using JRE we can only execute already developed application we cannot develop
new application.

4.JVM

-Java Virtual Machine.

-It is rersponsible to execute our java bytecode.

-It provides interpreter+JIT.

-Using it we can run java bytecode by converting them into current OS machine language.

5.JIT

-Just In Time compiler.

-It is responsible to help interpreter for executing java bytecode fast.

-It will improve performance of java pogram execution.

Compiler And Interpreter

We generally write a computer program using a high-level language. A high-level language is


one that is understandable by us, humans. This is called source code.
However, a computer does not understand high-level language. It only understands the
program written in 0's and 1's in binary, called the machine code.
To convert source code into machine code, we use either a compiler or an interpreter.
Both compilers and interpreters are used to convert a program written in a high-level
language into machine code understood by computers. However, there are differences
between how an interpreter and a compiler works.

Compiler Vs Interpreter

Compiler Interpreter

Scans the entire program and translates the overall execution time is
JIT
it as a whole program into machine comparatively slower than compilers.
code at a time.

the overall execution time is the overall execution time is


comparatively faster than interpreters. comparatively slower than compilers.

complier

-The Just-In-Time compiler is one of the integral parts of the Java Runtime Environment.

-It is mainly responsible for performance optimization of Java-based applications at run time
or execution time.

-The main motto of the compiler is increasing the performance of an application for the end
user and the application developer.

-Compiler will compile the source code and generate bytecode.

-Interpreter will covert this bytecode into native code line by line.

-When code goes through JIT, JIT will optimize it.

-Byte code is the chief potential of Java’s WORA (Write once, run anywhere) environment.

-Speed of the Java application depends on the way the byte code gets converted to the
native machine code.

-In order to speed up the performance, JIT compiler communicates with JVM at the
execution time in order to compile

byte code sequences into native machine code.


-Basically, when using JIT Compiler, the native code is easily executed by the hardware
when compared to JVM

Interpreter. By doing so, there will be a huge gain in execution speed.

-When the JIT Compiler compiles the series of byte code, it performs certain optimizations.

This makes Java very efficient when it comes to execution and performance.

-JIT is Just In Time compiler.

-It is part of JRE.

-It compiles bytecode into machine code at runtime.

-Very frequently used code is compiled once and kept into memory.

-JIT performs optimization on code.

-JIT will identify at runtime which instructions are frequently used and keep them into
memory.So when next time when that same code occurs it will directly pick that up and
convert into native code without recompilation.

-it contains some optimization methods.

Java Program Execution Flow:

When we compile Java program using javac tool, the Java compiler converts the source
code into byte code.

What happens at compile time?


At compile time, the Java file is compiled by Java Compiler (It does not interact with OS) and
converts the Java code into bytecode

What happens at runtime?

At runtime, the following steps are performed:

Class Loader:

It loads .class file into memory.

Bytecode Verifier:

Checks the code fragments for illegal code

Interpreter:

Read bytecode stream then execute the instructions.

Creating Simple Hello Program:

To write the simple program, you need to open notepad by start menu -> All Programs ->
Accessories -> Notepad and write a simple program as shown below:

class Simple{
public static void main(String args[]){
System.out.println("Hello…");
}
}

As displayed the above, write the simple program of Java in notepad and saved it as
Simple.java. In order to compile and run the above program, you need to open the
command prompt by start menu -> All Programs -> Accessories -> command prompt.
When we have done with all the steps properly, it shows the following output:
- Save the above file as Simple.java.
- To compile:
Javac Simple.java
- To Execute:
Java Simple

Let's see what is the meaning of class, public, static, void, main, String[],
System.out.println().

- class :

keyword is used to declare a class in Java.

- public :

keyword is an access modifier that represents visibility. It means it is visible to all.

- static:

is a keyword. If we declare any method as static, it is known as the static method.

- void
It is a return type of method. It means it doesn’t return any value.

- main
it is a method. It is starting point of java program execution.

- String[] args or String args[] is used for command line arguments.


- System.out.println() is used to print statement. Here, System is a class, out is an
object of the PrintStream class, println() is a method of the PrintStream class.
Class and Objects:

Class:

- Class is a blue print or template from which objects are created.


- Object is an instance of class.

Why we write a class:

- Java is an object oriented programming language.


- To create an object first we need to define the properties which that object should
have.
- The properties and behaviour which we want to impart to the object are declared in
class. Hence class is called as blueprint of objects.

Coding standard for class name:

- Usually class are nouns.


- Class name starts with upper case letter.
- If using multiple words, then each first letter of word should start in uppercase.
For ex.class Student, class String, class StringBuffer, class EmployeeData etc.

Types of classes:

1. Built-in classes.
2. User defined classes.

1. Built – in classes:
- Java language has provided set of predefined classes within predefined package.
- This classes are required commonly in all types of projects hence they are provided
by default in java.
- Majorly used built-in classes are:
1. java.lang.String
2. java.lang.Exception
3. java.lang.Object
4. java.lang.Class
5. java.lang.Date
2. User defined or custom classes :
As the name suggest a custom or user defined class is a class that is created by
user/developer.

Syntax:
<Access-specifier> class <ClassName>{

Class body
}
A java class generally consist of:
1. Fields/ variables
2. Methods
3. Constructor
4. Block
5. Nested class

Rules for class:

1. A Java class must have the class keyword followed by the classname.
2. The class name must start with capital letter and if using more than one word as class
name every first letter of each word should be capital.
3. There should not be any spaces or special characters used in class name except $
symbol and _.
4. It can extend only one parent class. By default all classes extend java.lang.object
directly or indirectly.
5. A class may optionally implement any number of interfaces separated by commas.
6. The class’s members must be always declared within a set of curly braces{}.
7. Class containing main method that class known as main class.

Objects:

- Object is a real world entity which has its own property/state and behavior.
- So object contains of the following things:
1. State :
This is represented by attribute and properties of object.
2. Behaviour:
This is defined by methods of the object.
Ex. Mobile is an object which has state/property such as color, model number,
RAM, etc.
Behaviour such as calling, messaging, etc.

Syntax to create an object:


<ClassName> <Objectname> = new <ClassName>();
Ex. Student student = new Student();

Example- Hello world program


public class Hello
{
public static void main(String[] args){
System.out.println(“Hello world….”);
}
}
Output:
Hello world….
Details steps of Hello world program

You can see the folder structure.

For creating class right click on src>>new>>class


Right the program and run then you get the output

You can run the program and see the output

Identifier:
A name in java program is called identifier.
It may be class name, method name, variable name and label name.
Example:
Class Test
{
Public static void main (String[] args)
{
int x=10;
}
}
In above program highlighted and inderlined are identifiers.
Test – classname
main – method name
String – class name
args – array name
x - variable name.
Rules to define java identifiers:
Rule 1: The only allowed characters in java identifiers are:
1) a to z
2) A to Z
3) 0 to 9
4) _ (underscore)
5) $ Rule
If we are using any other character we will get compile time error.
Example: 1) total_number-------valid
2) Total#------------------invalid
Rule 2: identifiers are not allowed to starts with digit.
Example: 1) ABC123---------valid
2) 123ABC---------invalid
Rule 3: java identifiers are case sensitive of course java language itself treated as case
sensitive language.
Example: class Test
{
int number=10;
int Number=20;
int NUMBER=20; we can differentiate with case.
int NuMbEr=30;
}
Rule 4: There is no length limit for java identifiers but it is not recommended to take more
than 15 lengths.

Rule 5: We can't use reserved words as identifiers.


Example: int if=10; --------------invalid
Rule 6: All predefined java class names and interface names we use as identifiers.
Example 1: class Test
{
public static void main(String[] args)
{
int String=10;
System.out.println(String);
}
}
Output: 10
Even though it is legal to use class names and interface names as identifiers but it is not a
good programming practice.
Reserved Words
In java some identifiers are reserved for some functionality or meaning such type of
reserved identifiers are called reserved words.

Reserved words for data types: (8)


1) Byte
2) Short
3) Int
4) Long
5) Float
6) Double
7) Char
8) Boolean
Reserved words for flow control:(11)
1) if
2) else
3) switch
4) case
5) default
6) for
7) do
8) while
9) break
10) continue
11) return

Keywords for modifiers:(11)


1) public
2) private
3) protected
4) static
5) final
6) abstract
7) synchronized
8) native
9) strictfp(1.2 version)
10) transient
11) volatile

Keywords for exception handling:(6)


1) try
2) catch
3) finally
4) throw
5) throws
6) assert(1.4 version)

Class related keywords:(6)


1) class
2) package
3) import
4) extends
5) implements
6) interface

Object related keywords:(4)


1) new
2) instanceof
3) super
4) this

Void return type keyword:


If a method won't return anything compulsory that method should be declared with
the void return type in java.

Unused keywords:
goto: Create several problems in old languages and hence it is banned in java.
Const: Use final instead of this. By mistake if we are using these keywords in our
program we will get compile time error.

Reserved literals:
1) true values for boolean data type.
2) false
3) null----------------- default value for object reference.

Program: Program to print student details.


Java program to print roll number, name and course of the student.

public class Student {

int rno = 1;
String name = "Shraddha";
String course = "MCA";

public static void main(String[] args) {


// TODO Auto-generated method stub

Student student = new Student();


System.out.println("rollno:"+student.rno);
System.out.println("name:"+student.name);
System.out.println("course:"+student.course);

Output:
rollno:1
name:Shraddha
course:MCA

Character set:
A character set in Java is a set of alphabets, letters, and some special characters that are
valid in java programming language. Java language uses the character sets as the building
block to form the basic elements such as identifiers, variables, array, etc in the program.
These are as follows:
 Letters: Both lowercase(a,b,c,d,e,etc.) and uppercase(A,B,C,D, E,etc.)letters.
 Digits:0,1,2,3,4,5,6,7,8,9.
 Special symbols:_,(,),{,},[,],+,-,*,/,%,!,&,|,~,^,,$,#,?, Comma(,),Dot(.),Colon(:),Semi-
colon(;),Single quote(‘),Double quote(“),Backslash(\)

Data types:
- In java every variable has a type, every expression has a type and all types are strictly
defined.
- Moreover, every assignment should be checked by the compiler by the type
compatibility hence java language is considered as strongly typed programming
language.
- All variables must be declared before its use.
- Data types specify the different sizes and values that can be stored in the variable.
- There are two types of data types in Java:

1)Primitive Datatype (Already defined in Java)


 This are the datatype which are predefined in Java
 For ex. Boolean, int, long, etc

2)Non-Primitive Datatype (User/Programmer defined)


 Programmer defines it. Not already defined in Java, except String)
 Array, class, etc. For ex. Student, Employee, etc.

Data type Size Range Corrsponding Default value


wrapper class
byte 1 byte -2^7to2^7-1 Byte 0
(-128 to 127)
short 2 bytes -2^15to2^15-1 Short 0
(-32768 to
32767)
int 4 bytes -2^31 to 2^31- Integer 0
1
(-2147483648
to
2147483647)
long 8 bytes -2^63to2^63-1 Long 0
float 4 bytes -3.4e38 to Float 0.0
3.4e38
double 8 bytes -1.7e308 to Double 0.0
1.7e308
boolean NA Not applicable Boolean false
(but allowed
values true |
false)
char 2 bytes 0to65535 Character Blank space

Program : Java Program to Demonstrate Char Primitive Data Type

class DemoDatatypes {
public static void main(String args[]){
char a = 'G';
int i = 89;
byte b = 4;
short s = 56;
double d = 4.355453532;
float f = 4.7333434f;
long l = 12121;
System.out.println("char: " + a);
System.out.println("integer: " + i);
System.out.println("byte: " + b);
System.out.println("short: " + s);
System.out.println("float: " + f);
System.out.println("double: " + d);
System.out.println("long: " + l);
}}
Output:
char: G
integer: 89
byte: 4
short: 56
float: 4.7333436
double: 4.355453532
long: 12121

Variables:
- Variable is name given to memory location where data is stored in memory.
- Variable should always be declared before its use without declaring variable you cannot
use it in your program.
- Variable should be declared with proper datatype of the data being stored in that.

Syntax:
Datatype variable_name;
Example – int number;
float percentage;
Declaration of the variable:
Declaration is just declaring the variable name with its data type.
Datatype variable_name;
Ex. int number;
float percentage;
Initialization of variable:
Initialization means assigning the value to variable.
The value should be correctly assigned as per the type of data type mentioned.
Datatype variable_name = value;
Ex. int number = 10;

Rules/ coding standards for naming variable:


1. Usually, variable names are nouns.
2. Variable name should start with lower case letters.
Ex-student, name, city, etc
3. If variable name contains more than 1 word then 1st letter of each word should be
capital(called as camelCase convention).
Ex. studentName, accountNumber, employeeAddress, etc.

Types of variables:
Variables in java are classified in 2 ways.
Division 1: Based on the type of value stored.

1. Primitive variables:
These are the variable that used to represent primitive values.
Ex. int x=10;

2. Reference variables:
These can be used to refer objects.
Ex. Student student = new Student();

Division 1: Based on the place of declaration and behaviour.


1. Instance variable (global variable).
2. Local variable.
3. Static variable.

1. Instance variable:
- Also called as global variables.
- They are declared inside a class but outside any method or block.
- Instance variable will be created at the time of object creation and destroyed at the
time of object destruction. Hence scope of instance variable will be same as scope of
object.
- For every object separate copy of instance variable created.
- Instance variable will be stored in heap area.
- Instance variable can be accessed directly in instance area but in static area we
cannot access it directly for that we need object.
Example:
public class Demo
{
introllNum=10;
public static void main(String[] args)
{
//System.out.println(rollNum); //Compile Error:non-static variable I
cannot be referenced from a static
context (invalid)

Demo demo=new Demo();


System.out.println(demo.rollNum);//10(valid)
}
}

Note: For the instance variables if we don’t perform initialization, JVM will always
provide default values.

2. Local variable:
- Sometimes programmer need temporary variable to meet their temporary
requirements in method or block.
- Local variables are also known as temporary variables.
- Local variables stored in stack area.
- Scope of local variable is exactly same as the scope of the method where they are
declared.
- We always have to initialize the local variable at the time of declaration. Otherwise, we
will get compile time error

Example:
public class Demo
{
public static void main(String[] args)
{
int x;
System.out.println(x); //Compile Error: Local variable x may not
have been initialised
}
}

Program: Demonstration of datatypes for checking default values and global variables
public class DemoDatatypes
{
int i;
float f;
boolean b;
long l;
byte bt;
short s;
char c;
double d;
public static void main(String[] args)
{
DemoDatatypes dd = new DemoDatatypes();
System.out.println(“default val of int:”+dd.i);
System.out.println(“default val of boolean:”+dd.b);
System.out.println(“default val of float:”+dd.f);
System.out.println(“default val of double:”+dd.d);
System.out.println(“default val of char:”+dd.c);
System.out.println(“default val of long:”+dd.l);
System.out.println(“default val of short:”+dd.s);
System.out.println(“default val of byte:”+dd.bt);
}
}
Output:
default val of int:0
default val of boolean:false
default val of float:0.0
default val of double:0.0
default val of char:
default val of long:0
default val of short:0
default val of byte:0

Methods:
Method is a block of statements used to perform some tasks. For ex. addition method can be
used to perform addition of numbers, calculate Percentage method can be used to calculate
percentage scored by student, etc
Basically methods are used to perform some operation.
Why do we write a method:
 We write a method to avoid rewriting a block of statement which will be required frequently
in our program/project.
 Suppose we have a block of statement in our program which calculates the addition of
numbers.
 In some another program we want to calculate the percentage. In this case we again need
to calculate the addition of numbers and divide it by number count and multiply by 100 to
calculate percentage. Due to this we are writing the same code in our program again and
again which increase the efforts and time required.
 If we define one method and write a logic for addition of marks then instead of writing a
entire code for addition of numbers again in another class, we will call this method into the
class and calculate the average.
 This is where method comes into picture.
Advantages of methods:
1. Code reusability
2. Reduce length of program.
3. Breaks large program into small pieces.
4. Increases readability of the program.
Coding Standard for Methods:
1. Method name should be either verb or verb-noun combination.
Ex. addition(), getStudentMarks(), getEmployeeData().
2. Method name should be in a camel case format. i.e if it contains more than one words
then first word should start with a lower case letter and remaining should start with
uppercase.
For ex. main(), addition(), getStudentDetails(), etc.
3. Method name should be some meaningful name so that other developer can
understand exactly what the purpose of the method is by reading method name itself.
4. Method body is enclosed within curly braces i.e.{}
Syntax:
<Access-specifier> <return-type> <method-name>(argument1, argument2,…)
{
// statement //Space between opening and closing curly braces method
called body or method block
}
Method Signature:
It includes method name and arguments.
Note:
1.Access specifier can be anything. i.e. public/private/protected/default.
2.Return type can be any type of datatype. i.e. primitive datatype like int, float, char, etc. or
non-primitive datatype like String, Student, etc. It can be also void.
3.Arguments can be of any type of datatype. i.e. primitive datatype like int, float, char, etc or
non-primitive datatype like String, Student, etc. Argument is optional hence method can be
without any argument.
Example.
1. public void demo()
{
//No need to return anything
}
2. public int demo()
{
// should return an integer
return 10;
}

3. public String demo()


{
//should return String
return “java”;
}

Types of Methods:
1. Pre-defined methods:
These are the methods already provided in java. Some frequently used code that
we need in almost every and most frequent applications are already written in
some methods and those are readily available to us.
Example. main() – public static void main(String[] args) this method is main entry
point of every java program. Without this our program cannot get executed.
Println() – this method to print our data on console.

2. User defined methods:


These are the methods that we develop.
These are again further classified:
1. Static Method.
2. Non static method.

1. Static Method:
- Any method that is declared with static keyword is called as static method.
- These are class level methods because they get loaded into memory at the time of
class loading.
- Static methods can be called using 3 ways:
a. By using class name – If you are calling your static method in another call then
you can call it by using class name.
b. Directly by using method name – If you are calling your static method within
same class then you can directly call using method name.
c. By using object – You can call static methods by using your class object as well
But the most preferable way to call your static methods are by using class
name or by directly using method name.

For ex:
public class Student {

int rno = 1;
String name = "Shraddha";
String course = "MCA";

public static void getStudentData()


{
Student s1 = new Student(); //we created
object bcz we are accessing global/instance
variables in static area and without object we can’t access it.
System.out.println("Rno:"+s1.rno);
System.out.println("Name:"+s1.name);
System.out.println("course:"+s1.course);
}

public static void main(String[] args) {


// TODO Auto-generated method stub

Student student = new Student();

//1st way to access static method - by classname


Student. getStudentData();

//2nd way to access static method - by method name


getStudentData();

//3rd way to access static method - by object


student.getStudentData();

}
}
b) Non static method:
- When we define a method without static keyword, then that method is called as non
static method.
- We can call this method by using object of class.
For ex.
public class Employee{
public static void main(String args[]){

public void getSalary(){


System.out.println("Employee salary is 80000");
}
//By creating a Object of class
Employee employee = new Employee();
employee.getSalary();
}
}
Output: Employee salary is 80000

Parameters and Arguments

Information can be passed to methods as parameter. Parameters act as variables inside the
method.

Parameters are specified after the method name, inside the parentheses. You can add as
many parameters as you want, just separate them with a comma.

The following example has a method that takes a String called fname as parameter. When
the method is called, we pass along a first name, which is used inside the method to print the
full name:

Flow Control Statements :


While programming, we need to manage the flow of the program execution.
To describe the order in which program statements will be executed, we have
flow control statements.

Flow control statements classification:


There are various types of flow control statements as follows:
Selection Statements:
Java Selection statements are used to executive a particular statement when
some condition is fulfilled or not.
Selective statement can be further classified as :
1. if – else
A) if-else
B) If-else ladder
C) Nested if
2. switch

A) if-else:
If-else is used to executive a statement/statements when a particular
condition is true or false.
Note : Note that while providing the condition for if else, it should be Boolean
type always.by mistake if we are providing any other type we will get "compile
time error
Syntax: It should be Boolean always, even if it’s some expression still
it’s net result should be of Boolean type

if(condition){
//if condition is true executive if block only
}
else{
//if condition is false then executive else block only
}
Example 1:
public class Demo {
public static void main(String args[]) {
int x = 0;
if (x) {
System.out.println("hello");
} else {
System.out.println("hi");
}
}
}
OUTPUT:
Compile time error: Demo.java:4:
incompatible types found : int
required: Boolean if(x)

Example 2:
public class Demo {
public static void main(String args[]) {
int x = 0;
if (x==0) {
System.out.println("hello");
} else {
System.out.println("hi");
}
}
}
OUTPUT:
hello

Note:

1) Curly braces after if and else are optional. In such case, we can write
only one statement after if and else , which should not be declarative
statement.
For ex:
if(true)
System.out.println("in if block");
else
System.out.println("in else block");

This is valid. Note there are no curely braces after if and else.But
there must be only one statement which should not be declarative
statement.
Ex2.
if(x)
int y=10; else
int z=100;

This is invalid as the statement after if else without curly braces are
declarative statements.

2) If can exist without else. Else block is optional.


For ex.
if(2<10){
System.out.println(“in if block”);
}
Output:
in if block
B) If-else ladder-
If we want to check multiple conditions out of which only one
conditions should be executed then we use if-else-if ladder

Eg-
public class IfElseLadder{
public static void main(String[] args){ int
marks=75;
if(marks>=50 && marks <60){
System.out.println(“D grade”);
}
else if(marks>=60 && marks <70){ System.out.println(“C grade”);
}
else if(marks>=70 && marks <80){ System.out.println(“B grade”);
}
else if(marks>80){ System.out.println(“A grade”);
}
else{
System.out.println(“Incorrect input”);
}}

Output- B
grade

C) Nested if statement{
if block within if block is called nested if.

Eg.
public class NestedIf{
public static void main(String[] args){
int num=50;
if(num>=25){
if(num>=50){
System.out.println(“number is greater than 50”);
}
}}}

2) switch:

If multiple options are available, then instead of using if- else-if ladder/if-
else multiple times we should go for switch statement as it improves the
readability of code.

Syntax:
switch(x){
case 1:
action1
case 2:
action2
...default:
default action
}
For ex.
int x=3;
switch(x){ case
1:
System.out.println(“Executing case 1”);
case 2:
System.out.println(“Executing case 2”);
case 3:
System.out.println(“Executing case 3”);
default:
System.out.println(“Executing default case ”);
}
Output:
Executing case 3
Note:
1) If no case is matched then default case will be executed.
2) Until 1.4 version the allow types for the switch argument
are byte, short, char, int but from 1.5 version onwards the
corresponding wrapper classes (Byte,
Short,Character, Integer) ,String ,enum also allowed.
3) Curly braces are mandatory.(except switch case in all
remaining cases curly
braces are optional )
4) Both case and default are optional.
5) Every statement inside switch must be under some
case (or) default. Independent statements are not
allowed.
6) Every case label should be within the range of switch
argument type.
7) Duplicate case labels are not allowed.
8) Within the switch statement if any case is matched from
that case onwards all statements will be executed until
end of the switch (or) break. This is call "fall-through"
inside the switch .
9) Within the switch we can take the default only once
10) Within the switch we can take the default anywhere, but
it is convention to take default as last case.
11) Duplicate case values are not allowed.
12) The value for a case must be of the same data type as
the variable in the switch.
13) The value for a case must be constant or literal.
Variables are not allowed.
14) The break statement is used inside the switch to
terminate a statement sequence.
15) The break statement is optional. If omitted, execution
will continue on into the next case.

Looping statements(Iteration Statements):


This type of statement is used to execute a statement or set of
statements multiple times.

Iteration statement is further classified as:

1) for loop
• This is one of the most widely used loop.
• This loop is the best choice if the number of iterations is
already known.
Syntax:
for(initialization;conditionalexpression;increment/decrement)
{
Body
}

For loop have four sections:


a) Initialization Section:
• In this section, we declare the loop variable.
• This section is the starting point of for loop and is
executed only once.
• We can initialize multiple variables at the same time but
should be of same type.
• We can write any valid java statement here, even
System.out.println()
For ex.
1. for(int j=10, j=20;…;….){
//valid
}
2. for(int j=10, int j=20;…;….){
//invalid }
3. for(int j=10, boolean b=false;…;….){
//invalid
}
4. for(System.out.println(“Hi”);…;….){
//valid }
b) Conditional Check:
• We can take any java expression but should be of the
type Boolean.
• Conditional expression is optional and if we are not taking
any expression compiler will place true.

c) Increment and decrement section:


• This section is used to increase/decrease the value of
loop variable.
• Although we can use any valid java statement including
s.o.p also.
Note:

-All the section of for loop are optional.


-Curly braces are optional and without curly braces we can take only one
statement which should not be declaration statement.

For ex:
1. for( ; ; ){
System.out.println(“Hi”);
}

Output: Infinite time Hi.

2. int x=0;
for(System.out.println(“In initialization”); x<3 ;
System.out.println(“In increment/decrement”)){
System.out.println(“In for loop body”); x++;
}
Output:
In initialization In
for loop body
In increment/decrement In
for loop body
In increment/decrement In
for loop body
In increment/decrement

Unreachable statement in for loop:


There can be a compile time error of unreachable
statement while using for loop.
It happens when for loop will be executed infinitely and the next
statement after for loop won’t execute ever.

For ex.
for(int i=0;true;i++){
System.out.println(“In for loop body”);
}
System.out.println(“Outside for loop”);

Output:
Here System.out.println(“Outside for loop”) will give
compile time error as the for loop will run indefinitely and this
statement will never get a chance to execute.

1. while loop
• While loop is the best choice when the number of iterations are
not known in advance.

Syntax:

Eg- while(itr.hasNext()){

//body
}

• The Condition argument should be of Boolean type.


Otherwise we will get a compile time error.
• Curly braces are optional here also and without curly braces we
can write only one java statement which should not be a
declaration statement.
Eg1-
public class ExampleWhile{

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

System.out.println(“Hi”); //valid

}}

Eg2-

public class ExampleWhile{

public static void main(String[] args){

while(true)

int x=10; //invalid

• The argument to the while statement should be Boolean type. If


we are using any other type we will get compile time error.

Eg-

public class ExampleWhile{

public static void main(String[] args){

while(1){ //condition is not boolean

System.out.println(“Hi”);

}}
Output:

Compile time error

Incompatible types

Found: int

Required : boolean

Eg-

public class ExampleWhile{

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

//condition is boolean System.out.println(“Hi”);

}}

Output:

Hi will be printed infinite times.

Unreachable statement in while loop:


Like for loop, while loop can also have unreachable
statement.

For ex:
while(true){
System.out.println("Inside while loop");
}
System.out.println(“Outside while loop”);

Output:
Here it will be compile time error as Outside while loop statement will never get
a chance to execute as while loop will execute infinitely.

do-while loop:
If we want to execute a loop body atleast once, then we use do while loop.
Syntax:

• Curly braces are optional.


• If we use without curly braces then we should take exactly one
statement which should not be declarative statement.

For ex.
1. do{
System.out.println ("Hello");
}while(true);

Output:
Hello (infinite times)

2. do{
System.out.println ("Hello");
}while(false);

Output:
Hello

Unreachable statement in do while loop:


Like for and while loop, do-while loop can also have unreachable
statement.
For ex:
do{
System.out.println ("Hello");
}while(true);
System.out.println(“Outside do-while loop”);

Output:
Here it will be compile time error as Outside do
-while loop statement will never get a chance to execute as do-while loop
will execute infinitely.

Transfer / Jump Statements:

Break statement:
Break statement is used in following cases:
1) Inside loop when you want to break the loop execution under some
condition
• If you don’t want to continue the loop to execute if some
particular condition is met, then we use break within the loop.

For ex.
for(int i=0; i<10;i++){ if(i==4)
break;
System. out.println(“Hello ”+i);
}
System. out.println(“Outside for loop”);

Output:
Hello 0
Hello 1
Hello 2
Hello 3
Outside for loop

2) Inside switch to stop the fall through within switch


• Within the switch statement if any case is matched from that
case onwards all statements will be executed until end of the
switch (or) break. This is call "fall-through"
inside the switch
• Hence to avoid or stop fall-through we use break in switch.

For ex
1. Switch case without break:
int x=2;
switch(x){
case 1:
System.out.println("Case one"); case
2:
System.out.println("Case two"); case
3:
System.out.println("Case three");
case 4:
System.out.println("Case four");
default:
System.out.println("Default Case");
}
Output:

Case two
Case three
Case four
Default Case
2. Switch case with break:
int x=2; switch(x){
case 1:
System.out.println("Case one");
break;
case 2:
System.out.println("Case two");
break;
case 3:
System.out.println("Case three");
break;
case 4:
System.out.println("Case four");
break;
default:
System.out.println("Default Case");
}

Output:
Case two
Note:

If you use break statement at any other location apart from mentioned above,
then it will be a compile time error.

Continue Statement:

If you want to skip just current iteration and go to next iteration of loop instead
of skipping the entire loop execution then we use continue statement.

For ex:
1) Print all even number between 1 to 10. for(int
i=1; i<=10;i++){
if(i%2!=0)
continue;
System.out.println(i);
}
Output:
2
4
6
8
10

Note:
If you use continue statement at any other location apart from mentioned
above, then it will be a compile time error.
Packages-
Package is nothing but collection of classes and interface that works
together. Java.lang is default package in java. We can create our
custom packages also.

Why?
Suppose imagine, if you have large number of files in your project that is
deployed on server, now the code is released on production server. There
are bugs in specific files then how you can reach to that file without packages
is very difficult. If you have packages then it will get very easy to go specific
folder and found that file. That’s why packages comes into picture.

Advantages
Packages helps to resolves naming confliction
Reusability- we can placed the common code into one folder and reuse it.
Maintenance- if any new developer/tester joined your company then it will
be easy to find the file which they wanted.

Syntax-
com.wipro.jpmorgan.insurance.policy.e
ducation

Here,
Package are generally starts with com folder.wipro is your company name.

jpmorgan is your client


name. insurance is your
project name. policy is your
module name. education is
your sub-module name.
Note- All alphabets are starts with small case letters only.
import-
When we use one class within another class then go for import statement.
Example- suppose we have two different classes Test & Example in different
packages.

package com.wipro;

public class Test {

//method or variable
public void m1() {

System.out.println("this is the m1 method");


}

package com.wipro.jpmorgan;public

class Example {

public static void main(String[] args) {

Test test= new Test();


}

In the test class, we are calling the method of test class, so we need
to use the import statement here. Otherwise it will give compile time
error

To resolve this issue, we need to import the highlighted line that is Import
import
’Test’(com.wipro) by just clicking on it.
Different ways for import-
import com.wipro.Test; //correct
import com.wipro.*; //correct- it will import the all the classes.
import com.wipro; //wrong
Scanner in java
Scanner is a class in java.util package used for obtaining the input of the
primitive types like int, double, etc. and strings. It is the easiest way to read
input in a Java program.
• To create an object of Scanner class, we usually pass the predefined
object System.in.

• To read numerical values of a certain data type, the method to use


is nextXYZ(). For example, to read a value of type short, we can use
nextShort() and so on.

• To read strings, we use nextLine().

Program for using scanner.


Example-1
import

java.util.Scanner; public

class Demo {

public static void multiplication(int no) {

for (int i = 1; i <= 10; i++)


{ int c = no * i;
System.out.println(no + "*" + i + "=" + c);
}

public static void main(String[] args) {

System.out.println("Enter the number for multiplication>>"); Scanner scanner =


new Scanner(System.in);
int x = scanner.nextInt();
System.out.println("value>>" + x);
multiplication(x);

}
Example-2
import

java.util.Scanner;

public class Test{

public int add(int a, int


b) { int c = a + b;
return c;

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.println("Enter the first


number>>"); int firstNumber =
scanner.nextInt();

//take the input from user use nextInt();

System.out.println("Enter the second


number>>"); int secondNumber =
scanner.nextInt();

System.out.println("first Number>>"+firstNumber);
System.out.println("second Number>>"+secondNumber);

Test test = new Test();

int add=test.add(firstNumber, secondNumber);


System.out.println("Addition>>"+add);
}

You might also like