0% found this document useful (0 votes)
6 views

Java Unit-1

Uploaded by

23wj1a05m1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Java Unit-1

Uploaded by

23wj1a05m1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

SYLLABUS:

UNIT - I
Object oriented thinking and Java Basics- Need for oop paradigm, summary of oop concepts, coping with
complexity, abstraction mechanisms. A way of viewing world – Agents, responsibility, messages, methods,
History of Java, Java buzzwords, data types, variables, scope and lifetime of variables, arrays, operators,
expressions, control statements, type conversion and casting, simple java program, concepts of classes, objects,
constructors, methods, access control, this keyword, garbage collection, overloading methods and constructors,
method binding, inheritance, overriding and exceptions, parameter passing, recursion, nested and inner classes,
exploring string class.

UNIT - II
Inheritance, Packages and Interfaces – Hierarchical abstractions, Base class object, subclass, subtype,
substitutability, forms of inheritance specialization, specification, construction, extension, limitation,
combination, benefits of inheritance, costs of inheritance. Member access rules, super uses, using final with
inheritance, polymorphism- method overriding, abstract classes, the Object class. Defining, Creating and
Accessing a Package, Understanding CLASSPATH, importing packages, differences between classes and
interfaces, defining an interface, implementing interface, applying interfaces, variables in interface and extending
interfaces. Exploring java.io.

UNIT - III
Exception handling and Multithreading-- Concepts of exception handling, benefits of exception handling,
Termination or resumptive models, exception hierarchy, usage of try, catch, throw, throws and finally, built in
exceptions, creating own exception subclasses. String handling, Exploring java.util. Differences between
multithreading and multitasking, thread life cycle, creating threads, thread priorities, synchronizing threads, inter
thread communication, thread groups, daemon threads. Enumerations, autoboxing, annotations, generics.

UNIT - IV
Event Handling: Events, Event sources, Event classes, Event Listeners, Delegation event model, handling mouse
and keyboard events, Adapter classes. The AWT class hierarchy, user interface components- labels, button,
canvas, scrollbars, text components, check box, checkbox groups, choices, lists panels – scrollpane, dialogs,
menubar, graphics, layout manager – layout manager types – border, grid, flow, card and grid bag.

UNIT - V
Applets – Concepts of Applets, differences between applets and applications, life cycle of an applet, types of
applets, creating applets, passing parameters to applets. Swing – Introduction, limitations of AWT, MVC
architecture, components, containers, exploring swing- JApplet, JFrame and JComponent, Icons and Labels, text
fields, buttons – The JButton class, Check boxes, Radio buttons, Combo boxes, Tabbed Panes, Scroll Panes,
Trees, and Tables.

Unit-1

Object oriented thinking and Java Basics: -

Need for oop paradigm :


 The object oriented paradigm is a methodology for producing reusable software
Components.

Object Oriented Programming is a paradigm that provides many concepts such as


inheritance, data binding, polymorphism etc.

Simula is considered as the first object-oriented programming language. The programming


paradigm where everything is represented as an object is known as truly object-oriented
programming language.

Smalltalk is considered as the first truly object-oriented programming language.

OOPs (Object Oriented Programming System)

Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is a
methodology or paradigm to design a program using classes and objects. It simplifies the software
development and maintenance by providing some concepts:

o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation

Object

Any entity that has state and behavior is known as an object. For example: chair, pen, table,
keyboard, bike etc. It can be physical and logical.

Class

Collection of objects is called class. It is a logical entity.

Inheritance

When one object acquires all the properties and behaviours of parent object i.e. known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Polymorphism

When one task is performed by different ways i.e. known as polymorphism. For example: to
convince the customer differently, to draw something e.g. shape or rectangle etc.

In java, we use method overloading and method overriding to achieve polymorphism.

Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.

Abstraction

Hiding internal details and showing functionality is known as abstraction. For example: phone
call, we don't know the internal processing.

In java, we use abstract class and interface to achieve abstraction.

Encapsulation
Binding (or wrapping) code and data together into a single unit is known as encapsulation. For
example: capsule, it is wrapped with different medicines.

A java class is the example of encapsulation. Java bean is the fully encapsulated class because all
the data members are private here.

Benefits of Inheritance

 One of the key benefits of inheritance is to minimize the amount of duplicate code.
 Inheritance can also make application code more flexible
 Reusability - facility to use public methods of base class without rewriting the same.
 Extensibility - extending the base class logic as per business logic of the derived class.

 Data hiding - base class can decide to keep some data private so that it cannot be
altered by the derived class.

A Way of viewing World- Agents


• The word agent has found its way into a number of technologies. It has been applied to aspects of artificial
intelligence research and to constructs developed for improving the experience provided by collaborative online
social environments (MUDS, MOOs, and the like). It is a branch on the tree of distributed computing. There are
agent development toolkits and agent programming languages.
• The Agent Identity class defines agent identity. An instance of this class uniquely identifies an agent. Agents
use this information to identify the agents with whom they are interested in collaborating.
• The Agent Host class defines the agent host. An instance of this class keeps track of every agent executing in
the system. It works with other hosts in order to transfer agents.
• The Agent class defines the agent. An instance of this class exists for each agent executing on a given agent
host.
• OOP uses an approach of treating a real world agent as an object.
• Object-oriented programming organizes a program around its data (that is, objects) and a set of well-defined
interfaces to that data.
• An object-oriented program can be characterized as data controlling access to code by switching the controlling
entity to data.

Responsibility
• In object-oriented design, the chain-of-responsibility pattern is a design pattern consisting of a source of
command objects and a series of processing objects..
• Each processing object contains logic that defines the types of command objects that it can handle; the rest are
passed to the next processing object in the chain. A mechanism also exists for adding new processing objects to
the end of this chain.

Primary motivation is the need for a platform-independent (that is, architecture- neutral) language that could
be used to create software to be embedded in various consumer electronic devices, such as microwave ovens
and remote controls.
• Objects with clear responsibilities
• Each class should have a clear responsibility.
• If you can't state the purpose of a class in a single, clear sentence, then perhaps your class structure needs
some thought.
• In object-oriented programming, the single responsibility principle states that every class should have a
single responsibility, and that responsibility should be entirely encapsulated by the class. All its services should
be narrowly aligned with that responsibility.
Messages
• Message implements the Part interface. Message contains a set of attributes and a "content".

• Message objects are obtained either from a Folder or by constructing a new Message
object of the appropriate subclass. Messages that have been received are normally retrieved from a folder
named "INBOX".
• A Message object obtained from a folder is just a lightweight reference to the actual message. The Message
is 'lazily' filled up (on demand) when each item is requested from the message.
• Note that certain folder implementations may return Message objects that are pre-filled with certain user-
specified items. To send a message, an appropriate subclass of Message (e.g., Mime Message) is instantiated,
the attributes and content are filled in, and the message is sent using the Transport. Send method.
• We all like to use programs that let us know what's going on. Programs that keep us informed often do so by
displaying status and error messages.
• These messages need to be translated so they can be understood by end users around the world.
• The Section discusses translatable text messages. Usually, you're done after you move a message String into
a Resource Bundle.
• If you've embedded variable data in a message, you'll have to take some extra steps to prepare it for
translation.
Methods
• The only required elements of a method declaration are the method's return type, name, a pair of
parentheses, (), and a body between braces, {}.
• Two of the components of a method declaration comprise the method signature—the method's name and
the parameter types.
• More generally, method declarations have six components, in order:
• Modifiers—such as public, private, and others you will learn about later.
The return type—the data type of the value returned by the method, or void if the method
does not return a value.

• The method name—the rules for field names apply to method names as well, but the convention is a little
different.

• The parameter list in parenthesis—a comma-delimited list of input parameters, preceded by their data
types, enclosed by parentheses, (). If there are no parameters, you must use empty parentheses.
• The method body, enclosed between braces—the method's code, including the declaration of local
variables, goes here.
Naming a Method
Although a method name can be any legal identifier, code conventions restrict method names. By convention,
method names should be a verb in lowercase or a multi-word name that begins with a verb in lowercase,
followed by adjectives, nouns, etc. In multiword names, the first letter of each of the second and following
words should be capitalized. Here are some examples:
run
run Fast
getBackground
getFinalData
compareTo setX isEmpty
Typically, a method has a unique name within its class. However, a method might have
the same name as other methods due to method overloading.

Overloading Methods
• The Java programming language supports overloading methods, and Java can distinguish between methods
with different method signatures. This means that methods within a class can have the same name if they
have different parameter lists (there are some qualifications to this that will be discussed in the lesson titled
"Interfaces and Inheritance").

Java Programming- History of Java

The history of java starts from Green Team. Java team members (also known as Green Team), initiated
a revolutionary task to develop a language for digital devices such as set-top boxes, televisions etc.

For the green team members, it was an advance concept at that time. But, it was suited for internet
programming. Later, Java technology as incorporated by Netscape.

Currently, Java is used in internet programming, mobile devices, games, e-business solutions etc. There are
given the major points that describes the history of java.

1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June 1991.
The small team of sun engineers called Green Team.

2) Originally designed for small, embedded systems in electronic appliances like set- top boxes.

3) Firstly, it was called "Greentalk" by James Gosling and file extension was .gt.

4) After that, it was called Oak and was developed as a part of the Green project.
Java Version History

Features of Java or Java Buzzwords


There is given many features of java. They are also known as java buzzwords. The Java Features
given below are simple and easy to understand.
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Dynamic
9. Interpreted
10. High Performance
11. Multithreaded
12. Distributed
Features of java

1. Java is simple :- Java is Easy to write and more readable and eye catching. Java has a concise, cohesive
set of features that makes it easy to learn and use. Most of the concepts are drew from C++ thus making
Java learning simpler.

2. Java is secure :-Java program cannot harm other system thus making it secure. Java provides a secure
means of creating Internet applications. Java provides secure way to access web applications.

3. Java is portable :-Java programs can execute in any environment for which there is a Java run-time
system.(JVM) Java programs can be run on any platform (Linux,Window,Mac) Java programs can be
transferred over world wide web (e.g applets)

4. Java is object-oriented :- Java programming is object-oriented programming language. Like C++ java
provides most of the object oriented features. Java is pure OOP. Language. (while C++ is semi object
oriented)

5.Java is robust:-Java encourages error-free programming by being strictly typed and performing run-
time checks.

6.Java is multithreaded :- Java provides integrated support for multithreaded programming.

7.Java is architecture-neutral Java is not tied to a specific machine or operating system architecture.
Machine Independent i.e Java is independent of hardware .

8. Java is interpreted Java supports cross-platform code through the use of Java bytecode. Bytecode can
be interpreted on any platform by JVM.

9. Java’s performance Bytecodes are highly optimized. JVM can executed them much faster
10.Java is distributed Java was designed with the distributed environment. Java can be transmit,run over
internet.

11.Java is 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.

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. Single Line Comment


2. Multi Line Comment
3. Documentation Comment

Java Single Line Comment

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

Syntax:

1. //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);

}
}

Output:

10

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);
}}

Output:

10

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

documentatio
n comment

*/

Example:

/** The Calculator class provides methods to get addition and subtraction 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;}

}
Data Types
Data types represent the different values to be stored in the variable. In java, there are two types of data types:

o Primitive data types


o Non-primitive data types

Data Type Default Value Default size

boolean false 1 bit

char '\u0000' 2 byte

byte 0 1 byte

short 0 2 byte

int 0 4 byte

long 0L 8 byte

float 0.0f 4 byte

double 0.0d 8 byte

Java Variable Example: Add Two Numbers


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

int a=10;
int b=10;
int c=a+b;
System.out.println(c);
}}

Output:20
Variables and Data Types in Java

Rules to create a variable:


1.They must not begin with a digit
2.Uppercase and lowercase are distinct. This means that the variable Total is not the same as total
or TOTAL
3.It should not be a keyword
4.white space is not allowed
5.Variable names can be of any length

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

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.

We will have detailed learning of these variables in next chapters.

Example to understand the types of variables in java


class A{
int data=50;//instance variable
static int m=100;//static
variable void method(){
int n=90;//local variable
}
}//end of class
Constants in Java

Integer constants:- refers to sequence of digits.There are three types of integers namely decimal integer,
octal integer and hexadecimal integer.

Decimal integes consist of a set of digits 0 through 9,preceded by an optional minus sign.
Ex: 123 -321 0 654321

Real constants:Integer numbers are inadequate to represent quantities that vary continuously,such as
diatances,heights ,temperatures ,prices and so on.
Ex:17.548

Single Character Constants:A single character constant contains a single character enclosed within a pair of
single quote marks.
Ex:’5’ ‘x’

String Constants:A string constant is a sequence of characters enclosed between double quotes.The characters
may be alphabets,digits ,special characters and blank spaces.
Ex:”hello” “1997” “X”

In java A constant is declared as follows :


final type symbolic-name = value;
Ex:final int STRENGTH = 100;
final int PASS_MARK = 50;
final float PI = 3.14;
They are written in capitals to visually distinguish them from normal variable names. This is only a convension
not a rule.

Scope and Life Time of Variables

The scope of a variable defines the section of the code in which the variable is visible. As a
general rule, variables that are defined within a block are not accessible outside that block. The
lifetime of a variable refers to how long the variable exists before it is destroyed. Destroying
variables refers to deallocating the memory that was allotted to the variables when declaring it.
There are three types of variables: instance variables, argument variables or class variables and
local variables.
Instance variables
Instance variables are those that are defined within a class itself and not in any method or
constructor of the class. They are known as instance variables because every instance of the
class (object) contains a copy of these variables. The scope of instance variables is determined
by the access specifier that is applied to these variables. We have already seen about it earlier.
The lifetime of these variables is the same as the lifetime of the object to which it belongs.
Object once created do not exist for ever. They are destroyed by the garbage collector of Java
when there are no more reference to that object. We shall see about Java's automatic garbage
collector later on.

int x=0;
{

. Block1

int n=5;
Block2
.
{
}
.

int m=10;

Argument variables or class variables


Block3
These are the variables that are defined in the header of a constructor or a method. The scope
of these variables is the method or constructor in which they are defined. The lifetime is
limited to the time for which the method keeps executing. Once the method finishes
execution, these variables are destroyed.

Local variables

A local variable is the one that is declared within a method or a constructor (not in the header).
The scope and lifetime are limited to the method itself.

One important distinction between these three types of variables is that access specifiers can
be applied to instance variables only and not to argument or local variables.
In addition to the local variables defined in a method, we also have variables that are defined
in bocks life an if block and an else block. The scope and is the same as that of the block itself.

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:

o Unary Operator-- ++,--


o Arithmetic Operator --- +,-,*,/,%
o shift Operator-- <<,>>, >>> ,<<<
o Relational Operator,--- <,>,>=,<=,==,!=
o Bitwise Operator --- &,|,!
o Logical Operator---- &&,||,!
o Ternary Operator and----? :
o Assignment Operator --- +=,-=,*=,/=,%=

Operators Hierarchy
Expressions
Expressions are essential building blocks of any Java program, usually created to produce a new
value, although sometimes an expression simply assigns a value to a variable. Expressions are
built using values, variables, operators and method calls.

Types of Expressions

While an expression frequently produces a result, it doesn't always. There are three types of
expressions in Java:

 Those that produce a value, i.e. the result of (1 + 1)


 Those that assign a variable, for example (v = 10)
 Those that have no result but might have a "side effect" because an expression can include
a wide range of elements such as method invocations or increment operators that modify
the state (i.e. memory) of a program.

 X=a-b/3+c*2-1

When a=9,b=12 and c=3 the statement becomes x=9-12/3+3*2-1

Finally x=10.

Type conversion and Type Casting

Widening or Automatic Type Conversion


Widening conversion takes place when two data types are automatically converted. This happens
when:
 The two data types are compatible.
 When we assign value of a smaller data type to a bigger data type.

For Example, in java the numeric data types are compatible with each other but no automatic
conversion is supported from numeric type to char or boolean. Also, char and boolean are not
compatible with each other.

Narrowing or Explicit Conversion


If we want to assign a value of larger data type to a smaller data type we perform explicit type
casting or narrowing.
 This is useful for incompatible data types where automatic conversion cannot be done.
 Here, target-type specifies the desired type to convert the specified value to.

float to int causes truncation of the fractional part.

double to float causes rounding of digits .

long to int causes dropping of the excess higher order bits

TYPE CASTING

The process of a local conversion is known as casting a value.The general form of a cast is
(type_name)expression

Where type_name is one of the standard data types.the expression may be a constant ,variable or an
expression.

Use of Casts
Java Enum

Enum in java is a data type that contains fixed set of constants.

It can be used for days of the week (SUNDAY, MONDAY, TUESDAY,


WEDNESDAY, THURSDAY, FRIDAY and SATURDAY) , directions (NORTH,
SOUTH, EAST and WEST)
etc. The java enum constants are static and final implicitly. It is available

from JDK 1.5. Java Enums can be thought of as classes that have fixed

set of constants.

Simple example of java enum


class EnumExample1{
public enum Season { WINTER, SPRING, SUMMER, FALL }

public static void


main(String[]args) {
for (Season s :
Season.values())
System.out.println(s);

Output:
WINTER SPRING

SUMMER

FALL

}}

Control Flow Statements


The control flow statements in Java allow you to run or skip blocks of code
when special conditions are met.

Java has very flexible three looping mechanisms. You can use one of the following three
loops:
while Loop
do...while Loop
for Loop
1.while loop
SYNTAX:
The syntax of a while loop is:
while(Boolean_expression)
{
//Statements
}
EXAMPLE

public class Test {


public static void main(String args[]) {

int x = 10;
while( x < 20 ) {
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}
}
}

This would produce the following result:


value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18

value of x : 19
2.do…while loop
SYNTAX:

The syntax of a do...while loop is:


do
{
//Statements
} while(Boolean_expression);

EXAMPLE:
public class Test {
public static void main(String args[]){

int x = 10;
do{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 20 );

}
}
This would produce the following result:
value of x : 10

value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15

value of x : 16
value of x : 17
value of x : 18
value of x : 19

3.The for Loop


A for loop is useful when you know how many times a task is to be repeated.:
SYNTAX:

The syntax of a for loop is:


for(initialization; Boolean_expression; update)

{
//Statements
}

EXAMPLE:

public class Test {


public static void main(String args[]) {
for(int x = 10; x < 20; x = x+1) {
System.out.print("value of x : " + x );

System.out.print("\n");
}
}
}
This would produce the following result:

value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14

value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

Branching statement:

There are two types of decision making statements in Java. They are:
if statements

switch statements

1. The if Statement:
SYNTAX:

The syntax of an if statement is:


if(Boolean_expression)
{
//Statements will execute if the Boolean expression is true
}
Example:
public class Test {
public static void main(String args[]){
int x = 10;
if( x < 20 ){

System.out.print("This is if statement");
}
}
}
This would produce the following result:
This is if statement

The if...else Statement:

An if statement can be followed by an optional else statement, which executes when the
Boolean expression is
false.

SYNTAX:

The syntax of an if...else is:


if(Boolean_expression){
//Executes when the Boolean expression is true
}else{
//Executes when the Boolean expression is false
}
Example:
public class Test {
public static void main(String args[]){
int x = 30;
if( x < 20 ){

System.out.print("This is if statement");
}else{
System.out.print("This is else statement");
}
}

}
This would produce the following result:
This is else statement.

The if...else if...else Statement:


SYNTAX:

The syntax of an if...else is:


if(Boolean_expression 1){
//Executes when the Boolean expression 1 is true
}else if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true
}else if(Boolean_expression 3){

//Executes when the Boolean expression 3 is true


}else {
//Executes when the none of the above condition is true.
}
EXAMPLE:

public class Test {


public static void main(String args[]){
int x = 30;
if( x == 10 ){
System.out.print("Value of X is 10");
}else if( x == 20 ){
System.out.print("Value of X is 20");
}else if( x == 30 ){

System.out.print("Value of X is 30");
}else{
System.out.print("This is else statement");
}
}

}
This would produce the following result:
Value of X is 30

Nested if...else Statement:

SYNTAX:

The syntax for a nested if...else is as follows:


if(Boolean_expression 1)
{
//Executes when the Boolean expression 1 is true

if(Boolean_expression 2)
{
//Executes when the Boolean expression 2 is true
}
}
You can nest else if...else in the similar way as we have nested if statement.
EXAMPLE:

public class Test {


public static void main(String args[]){
int x = 30;
int y = 10;
if( x == 30 ){

if( y == 10 ){
System.out.print("X = 30 and Y = 10");
}
}
}

}
This would produce the following result:
X = 30 and Y = 10.

The switch Statement:


SYNTAX:

The syntax is:


switch(expression){
case value1 :
//Statements
break; //optional

case value2 :
//Statements
break; //optional
//You can have any number of case statements.
default : //Optional
//Statements
}
EXAMPLE:

public class Test {

public static void main(String args[]){


char grade = 'C';
switch(grade)

{
case 'A' :
System.out.println("Excellent!");
break;
case 'B' :

case 'C' :
System.out.println("Well done");
break;
case 'D' :
System.out.println("You passed");

case 'F' :
System.out.println("Better try again");
break;
default :
System.out.println("Invalid grade");

}
System.out.println("Your grade is " + grade);
}
}
This would produce the following
Well done
Your grade is a C

Jump statements
The jump statements are break and continue.
The break keyword is used to stop the entire loop. The break keyword must be used
inside any loop or a switch

statement.
The break keyword will stop the execution of the innermost loop and start executing the
next line of code after
the block.

EXAMPLE:

public class Test {


public static void main(String args[]) {
int x;
for(x=0; x<=50; x++ ) {
if( x == 3 ) {

break;
}
System.out.print( x );
System.out.print("\n");
}

}
}
This would produce the following result:
0
1
2

The continue Keyword:


The continue keyword can be used in any of the loop control structures. It causes the
loop to immediately
jump to the next iteration of the loop.
In a for loop, the continue keyword causes flow of control to immediately jump to the
update statement.
In a while loop or do/while loop, flow of control immediately jumps to the Boolean
expression.
SYNTAX:

The syntax of a continue is a single statement inside any loop:


continue;
EXAMPLE:
public class Test {
public static void main(String args[]) {

int [] numbers = {10, 20, 30, 40, 50};


for(int x : numbers ) {
if( x == 30 ) {
continue;
}

System.out.print( x );
System.out.print("\n");
}
}
}

This would produce the following result:


10
20
40
50
simple java stand alone programs

class Sample{

public static void main(String[]args)


{
System.out.println(“hello world”);
}
}

o/p:hello world

Arrays
Java provides a data structure, the array, which stores a fixed-size sequential
collection of elements of the same type. An array is used to store a collection of
data, but it is often more useful to think of an array as a collection of variables of
the same type.

Instead of declaring individual variables, such as number0, number1, ..., and


number99, you declare one array variable such as numbers and use numbers[0],
numbers[1], and ..., numbers[99] to represent individual variables.

Types of Array in java


There are three types of array.
Single Dimensional Array
Multidimensional Array
Jagged Arrays (or) Asynchronous Arrays
Single Dimensional Array:
Declaring Array Variables:
To use an array in a program, you must declare a variable to reference the array, and
you must specify the type of array the variable can reference. Here is the syntax for
declaring an array variable:

dataType[] arrayRefVar; // preferred way.


or
dataType arrayRefVar[]; // works but not preferred way.

Example ;int []a={1,2,3,4}; // preferred way.

int a[]={1,2,3,4};// works but not preferred way.

You can create an array by using the new operator with the following syntax:

arrayRefVar = new dataType[arraySize];


int []a=new int[]{1,2,3,4};

Example:
Following statement declares an array variable, myList, creates an array of 10
elements of double type and assigns its reference to myList:

int [] myList = new int[10];


Following picture represents array myList. Here, myList holds ten int values and
the indices are from 0 to 9.

Example:
class Arraystr{
public static void main(String args[])
{
int num[3]={56,48,39}
for(int k=0;k<=3;k++)
{
if(num[k]>50 && num[k]<100)
{
System.out.println("the value is"+num[k]);
}
} } }

o/p: the value is 56

Example:
class Arraystr{
public static void main(String args[])
{
int num[3]={56,48,39}
for(int k:num)
{
if(k>50 && k<100)
{
System.out.println("the value is"+k);
}
} } }

o/p: the value is 56

Sorting of the number’s using array:


class Ascending_Order

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

int []a=new int[]{10,6,4,7,1};

int n=a.length;
int i,j,temp;
System.out.println("given list is ");
for(i=0;i<n;i++)

{
System.out.println("the numbers are"+a[i]);
}
for(i=0;i<n;i++)
{

for(j=i+1;j<n;j++)
{
if (a[i] > a[j])
{
temp = a[i];

a[i] = a[j];
a[j] = temp;
}
}
}
System.out.println("the sorted order is");
for(i=0;i<n;i++)
{
System.out.println("the numbers are"+a[i]);
}

}
}
O/P:the sorted order is :
1
4
6
7

10

Two dimentional arrays

import java.util.Scanner;
public class Twodim
{

public static void main(String[] args)


{

int row,col,i,j;
int [][]a=new int[5][5];

Scanner s=new Scanner(System.in);


System.out.println("enter the number of rows");
row=s.nextInt();
System.out.println("enter the number of cols");
col=s.nextInt();

System.out.println("enter the numbers");


for(i=0;i<row;i++)
{
for(j=0;j<col;j++)

{
a[i][j]=s.nextInt();
}
}

System.out.println("the numbers are");


for(i=0;i<row;i++)
{
for(j=0;j<col;j++)

{
System.out.println(a[i][j]+” ”);
}
System.out.println();
}
A[]={1,2,3,4,5}
A[0]=1
A[1]=2
A[2]=3
A[3]=4
A[4]=5

Jagged Arrays

A[0] 1 23
1 A[1] 4567
2 A[2] 8 9 10 11 12
class JaggedA
{
public static void main(String []args)
{
int i,j;
int[][]a=new int[3][];
a[0]=new int[2];
a[1]=new int[3];
a[2]=new int[4];
int count=0;
for(i=0;i<a.length;i++)
for(j=0;j<a[i].length;j++)
{
a[i][j]=count++;
}

for(i=0;i<a.length;i++)
{
System.out.println();

for(j=0;j<a[i].length;j++)
{
System.out.print(a[i][j]+" ");
}

}}
}

Classes and Objects:

Java is a true object oriented language and therefore the underlying structure of all java programs
is classes.Anything we wish to represent in a java program must be encapsulated in a class that
defines the state and behavior of the basic program components known as objects.Classes create
objects and objects use methods to communicate between them.

Class declaration

Class classname [extends superclassname]


{
[fields declaration]
[methods-declaration]
}

Field’s declaration

Ex: class rectangle


{
int length;
int width;
}

Method’s Declaration
Type methodname(parameter-list)
{
Method-body;
}

Ex:

void getdata(int x,int y)


{
length=x;
width=y;
}

Example Program :

class add

int len,wdth,c;

void getdata(int x,int y)

len=x;

wdth=y;

c=len*wdth;

// System.out.println(c);

void disp()

System.out.println(c);

public class Constrctore

public static void main(String []args)

add a=new add();

a.getdata(2,4);

a.disp();

}
Constructor:
Java supports a special type of method called a constructor ,that enables an object to initialize itself
when it is created .Constructors have the same name as the class itself .Secondly they do not
specify a return type ,not even void .This is because they return the instance of the class itself.

class abc
{
int len,wdth;
abc(int x,int y) //constructor
{
len=x;wdth=y;
}

Example : class add


{
int len,wdth,c;
add(int x,int y)
{
len=x;
wdth=y;

// System.out.println(c);
}
int rectArea()
{
return len*wdth;

}
// void disp()
//{
// System.out.println(c);
//}
}
public class Constrctore
{
public static void main(String []args)
{
add a=new add(10,20);
int b= a.rectArea();
System.out.println(b);
}
}

static fields and methods

a class basically contains two sections .one declares variables and the other declares
methods.These variables and methods are called instance variables and instance
methods.This is because every time the class is instantiated ,a new copy of each of them
is created.They are accessed using the objects(with dot oprator).

Ex: static int count ; -----static field


static int max(int x,int y);--static member

class oper
{
static float mul(float x,float y)
{
return x*y;
}
static float divide(float x,float y)
{
return x/y;
}
}
class Oneop
[
public static void main(String []args)
{
float a=oper.mul(4.0,5.0);
float b=oper.divide(a,2.0);
System.out.println(“b=”+b);
}
}

Nesting of methods
class nesting
{
int m,n;
nesting(int x,int y)
{
m=x; n=y;
}
int largest()
{
if (m>=n)
return(m);
else
return(n);
}
void display()
{
int large=largest();
System.out.println("the largest value is="+large);
}
}
public class NestTest
{
public static void main(String[]args)
{
nesting nest=new nesting(50,40);
nest.display();
}
}

Understanding Java Access Modifiers


Let's understand the access modifiers in Java by a simple table.

Access Modifier within class within package outside package by subclass only outside
package

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

Private

class A{
private int data=40;
private void msg()
{
System.out.println("Hello java");}
}

public class Simple{


public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}

Role of Private Constructor

If you make any class constructor private, you cannot create the instance of that class from outside
the class. For example:

class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}

Protected

package pack;
public class A
{
protected void msg()

{
System.out.println("Hello");}

}
package mypack;
import pack.*;

class B extends A{
public static void main(String args[])
{
B obj = new B();
obj.msg();
}
}

The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.

package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}

package mypack;
import pack.*;

class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}

Constructor overloading
A constructor initializes an object immediately upon creation. It has the same name as the class in
which it resides and is syntactically similar to a method. Once defined, the constructor is
automatically called when the object is created, before the new operator completes. Constructors
look a little strange because they have no return type, not even void.

class Box

{
double width, height, depth;

Box()

{
width = height = depth = 0;

Box(double len)
{

width = height = depth = len;

Box(double w, double h, double d)

width = w;

height = h;

depth = d;

double volume()
{

return width * height * depth;


}

public class Test


{

public static void main(String args[])

Box mybox1 = new Box(10, 20, 15);


Box mybox2 = new Box();

Box mycube = new Box(7);

double vol;

vol = mybox1.volume();

System.out.println(" Volume of mybox1 is " + vol);

vol = mybox2.volume();
System.out.println(" Volume of mybox2 is " + vol);

vol = mycube.volume();
System.out.println(" Volume of mycube is " + vol);

Recursion in java

Recursion in java is a process in which a method calls itself continuously. A method in java
that calls itself is called recursive method.

public class RecursionExample1


{
static void p(){
System.out.println("hello");
p();

public static void main(String[] args) {


p();
}
}

class Factorial {
static int factorial( int n ) {
if (n != 0) // termination condition
return n * factorial(n-1); // recursive call
else
return 1;
}

public static void main(String[] args) {


int number = 4, result;
result = factorial(number);
System.out.println(number + " factorial = " + result);
}
}

class facto
{

static int factorial(int n)


{
if (n==1)
return 1;
else
return(n*factorial(n-1));
}

public static void main(String[]args)


{
System.out.println(factorial(5));
}
}

THIS reference

The this is a keyword in Java which is used as a reference to the object of the current class, with
in an instance method or a constructor. Using this you can refer the members of a class such as
constructors, variables and methods.

class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
rollno=rollno;
name=name;
fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis1{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}

class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}

class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}

Garbage collection
Since objects are dynamically allocated by using the new operator,how such objects are destroyed
and their memory released for later reallocation. In some languages, such as traditional C++,
dynamically allocated objects must be manually released by use of a delete operator. Java takes a
different approach; it handles deallocation automatically. The technique that accomplishes this is
called garbage collection.

It works like this:


when no references to an object exist, that object is assumed to be no longer needed, and the
memory occupied by the object can be reclaimed. There is no need to explicitly destroy objects.
Garbage collection only occurs sporadically (if at all) during the execution of your program. It will
not occur simply because one or more objects exist that are no longer used.
class abc

int c;

void add(int x,int y)

c=x+y;

System.out.println("the value is"+c);

public class Example

public static void main(String[]args)

for(int i=0;i<1000;i++)

abc a=new abc();

a.add(i,i);

nested and inner classes:

In Java, it is also possible to nest classes (a class within a class). The purpose
of nested classes is to group classes that belong together, which makes your
code more readable and maintainable.
To access the inner class, create an object of the outer class, and then create
an object of the inner class:

class OuterClass {
int x = 10;

class InnerClass {
int y = 5;
}
}

public class Main {


public static void main(String[] args) {
OuterClass myOuter = new OuterClass();
OuterClass.InnerClass myInner = myOuter.new InnerClass();
System.out.println(myInner.y + myOuter.x);
}
}
Program to display the characters

class Demostring

public static void main(String[]args)

char []a=new char[]{'d','e','g','h','k'};

int n=a.length;

System.out.println("length is"+n);

for(int i=0;i<n;i++)

System.out.print(a[i]+" ");

}
}

Program on the string methods:-


class Abc

public static void main(String[]args)

String s1="WELCOME TO java PROGRAMMING ";

String s2=s1.toLowerCase();

System.out.println(s2);

String s3=s1.toUpperCase();

System.out.println(s3);

String s4=s1.replace('j','n');

System.out.println(s4);

System.out.println(s5);

String s6="hello";

String s7="hello";

boolean b=s6.equals(s7);

System.out.println(b);

String s8="HELLO";

boolean c=s6.equalsIgnoreCase(s8);

System.out.println(c);

String s9=s8.concat(s1);

System.out.println(s9);

}
Sorting of Strings

import java.util.*;

public class JavaExample

public static void main(String[] args)

int count;

String temp;

Scanner scan = new Scanner(System.in);

//User will be asked to enter the count of strings

System.out.print("Enter number of strings you would like to enter:");

count = scan.nextInt();

String str[] = new String[count];

Scanner scan2 = new Scanner(System.in);

System.out.println("Enter the Strings one by one:");

for(int i = 0; i < count; i++)

str[i] = scan2.nextLine();

scan.close();

scan2.close();

//Sorting the strings


for (int i = 0; i < count; i++)

for (int j = i + 1; j < count; j++) {

if (str[i].compareTo(str[j])>0)

temp = str[i];

str[i] = str[j];

str[j] = temp;

//Displaying the strings after sorting them based on alphabetical order

System.out.print("Strings in Sorted Order:");

for (int i = 0; i <= count - 1; i++)

System.out.print(str[i] + ", ");

You might also like