0% found this document useful (0 votes)
9 views67 pages

Part 1

The document provides an introduction to Java programming, covering its core concepts, features, and applications. It details the Object-Oriented Programming principles, Java's evolution, and its various versions, highlighting its platform independence and security features. Additionally, it outlines the basic structure of a Java program and the role of the Java Virtual Machine (JVM) in executing Java applications.

Uploaded by

ozrehan06
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views67 pages

Part 1

The document provides an introduction to Java programming, covering its core concepts, features, and applications. It details the Object-Oriented Programming principles, Java's evolution, and its various versions, highlighting its platform independence and security features. Additionally, it outlines the basic structure of a Java program and the role of the Java Virtual Machine (JVM) in executing Java applications.

Uploaded by

ozrehan06
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 67

Introduction to Course , Course Outcomes and Objectives

1. Introduction to Java
2. OOP Concepts / Principles
3. Implementing java program
4. Java Buzzwords
5. JVM
6. Data types
7. Variables
8. Type conversion & Type casting
9. Operators
10. Control statements
11. Arrays
12. Class, Object and Methods
13. Constructors
14. This keyword
15. Static keyword
16. String class
17. StringBuffer class
18. String Tokenizer

Note:
1. If you use Mobile – Dcoder Android
2. If you use Laptop/Desktop with internet – onlinegdb.com(online compiler)
3. If you use Laptop/Desktop without internet- Install Jdk 8 or above version.
Introduction to java
1.JAVA introduction:-

Author : James Gosling Ex:- Class Test


Vendor : Sun Micro System {
Type : open source & free software Public static void main (String [] args)
Initial Name : OAK language {
Present Name : java System.out.println (“welcome to java language”);
Extensions : .java & .class }
Initial version : jdk 1.0 (java development kit) }
Operating System : multi Operating System Compilation :- javac FileName.java
Implementation Lang : c, cpp…… Execution :- java Class Name
Symbol : coffee cup with saucer Output :- welcome to java language
Objective : To develop web applications
SUN : Stanford Universally Network
Slogan/Motto : WORA (write once run anywhere)
importance of core java:-
1) Java is used to develop Desktop Applications such as Media Player, Antivirus etc.
2) Java is Used to Develop Web Applications such as irctc.co.in etc.
3) Java is Used to Develop Enterprise Application such as Banking applications.
4) Java is Used to Develop Mobile Applications.
5) Java is Used to Develop Embedded System.
6) Java is Used to Develop Smart Cards.
7) Java is Used to Develop Robotics.
8) Java is used to Develop Games etc.

Parts of the java language:-


1) J2SE/JSE(java 2 standard edition)
2) J2EE/JEE(java 2 enterprise edition)
3) J2ME/JME(java 2 micro edition)

• J2SE:- By using j2SE we are able to develop the standalone applications.


Ex:- notepad, WordPad, paint, Google Talk………..etc.
• J2EE:- By using j2EE we are able to develop the web based applications.
Ex:- Gmail, yahoo mail, bank, reservation…………etc.
• J2ME:- By using j2ME we are able to develop the applications that only run on mobile devices
Technology:- Technologies depended on java:
1. J2SE
2. J2EE
3. J2ME Adv java
Frame works:- Structs
1. Struts
Hibernate
2. Spring
3. Hibernate Webservices
Servers:- Spring
1. Tomcat
SAP
2. Glassfish
3. Jboss Salesforce
4. WebLogic
Cloud computing
5. WebSphere
Android
IDE(integrated development environment):-
1. Eclipse Selenium
2. NetBeans
Hadoop
3. JDeveloper
Database :- TIBCO
Oracle MySQL
What is Java?
Java is a programming language and a platform.
 Java is a high level, robust, secured and object-oriented programming language.

Where it is used?
1. Desktop Applications such as acrobat reader, media player, antivirus etc.(Window
Applications)
2. Web Applications such as irctc.co.in, cleartrip.com etc.
3. Enterprise Applications such as banking, e-commerce applications.
4. Mobile Applications (J2ME)
5. Embedded System
6. Smart Card
7. Robotics
8. Games etc.
Types of Java Applications
1) Standalone Application
It is also known as desktop application or window-based application. An application that
we need to install on every machine such as media player, antivirus etc. AWT and Swing
are used in java for creating standalone applications. (J2SE)
2) Web Application
An application that runs on the server side and creates dynamic page, is called web
application. Currently, servlet, jsp, struts, jsf etc. technologies are used for creating web
applications in java. (J2SE)
3) Enterprise Application
An application that is distributed in nature, such as banking applications etc. It has the
advantage of high level security, load balancing and clustering. In java, EJB is used for
creating enterprise applications. (J2EE)
4) Mobile Application
An application that is created for mobile devices. Currently Android and Java ME are used
for creating mobile applications. (J2ME)
Evolution of Java
Currently, Java is used in internet programming, mobile devices, games, e-business
solutions etc.
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 "Green talk" 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.
Why sun choosed "Oak" name?
5) Why Oak?
Oak is a symbol of strength and choosen as a national
tree of many countries like U.S.A., France, Germany,
Romania etc.
6) In 1995, Oak was renamed as "Java" because it was
already a trademark by Oak Technologies.
Why sun choose "Java" name?
7) Why they choosed java name for java language?
The team gathered to choose a new name. The suggested words were "dynamic",
"revolutionary", "Silk", "jolt", "DNA" etc. They wanted something that reflected the
essence of the technology: revolutionary, dynamic, lively, cool, unique, and easy to spell
and fun to say.
According to James Gosling "Java was one of the top choices along with Silk". Since java
was so unique, most of the team members preferred java.
8) Java is an island of Indonesia where first coffee was produced (called java coffee).
9) Notice that Java is just a name not an acronym.
10) Originally developed by James Gosling at Sun Microsystems (which is now a
subsidiary of Oracle Corporation) and released in 1995.
11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.
12) JDK 1.0 released in(January 23, 1996).
Java Version History
There are many java versions that have been
released. Current stable release of Java is Java
SE 8.

1. JDK Alpha and Beta (1995) 12. Java SE 10(March, 20th 2018)
2. JDK 1.0 (23rd Jan, 1996) 13. Java SE 11 (18th March, 2014)
3. JDK 1.1 (19th Feb, 1997) 14. Java SE 12(March, 19th 2019)
4. J2SE 1.2 (8th Dec, 1998) 15. Java SE 13(September, 17th 2019)
5. J2SE 1.3 (8th May, 2000) 16. Java SE 14(March, 17th 2020)
6. J2SE 1.4 (6th Feb, 2002) 17. Java SE 15(September 2020)
7. J2SE 5.0 (30th Sep, 2004) 18. Java SE 20(March 2023)
8. Java SE 6 (11th Dec, 2006) 19. Java SE 21.0.3 (April 16, 2024)
9. Java SE 7 (28th July, 2011)
10. Java SE 8 (18th March, 2014)
11. Java SE 9 (September, 21st 2017)
Oops concept/principles
2. OOPs Concepts / OOPs Principles

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
Object is a real world entity that has state and behavior.
It is an instance of class.
Object is a physical entity.
For example: chair, pen, table, keyboard, bike etc. It can be physical and logical.
Class:
Collection of variables and methods.
Collection of objects is called class. It is template or blue print of objects.
It is a logical entity.
Inheritance
Process of getting properties and behaviors of one class to another class is known as inheritance.
It provides code reusability.
Properties – variables, behaviors - methods
Ex: Property transfer from Grand Parent to Parent – to children.
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.
i.e The process of representing one form in multiple forms is known as polymorphism.
e.g. When we are in class – student , When we are in Market – Customer, When we are in Home – Son/Daughter.
In java, we use method overloading and method overriding to achieve polymorphism
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.
Exposing only the required essentials characteristics & behavior with respect to the context.
Shows important things to the user and hide the internals details.
e.g. ATM , BIKE , MOBILE PHONES
Encapsulation
Process of binding (or wrapping) code and data as a single unit is known as encapsulation.
Date Hiding + Abstraction.
For example: capsule, it is wrapped with different medicines, Power Steering Car (Internally lot of
Components tightly Coupled together)
A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the
data members are private here.
Java Buzzwords
4. Features of Java / Java Buzz Words
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 &
Multithreaded
11. Distributed
1. Simple
• According to Sun, Java language is simple because:
• Syntax is based on C & C++.
• removed many confusing and/or rarely-used features e.g., explicit pointers, operator
overloading, multiple inheritance etc.
• No need to remove unreferenced objects because java has Automatic Garbage Collection.
• Java takes less time to compile and execute the program.

2. Object-oriented
• Java is object oriented technology because to represent total data in the form of object.
• By using object reference we are calling all the methods, variables which is present in that
class.
• the total java language is dependent on object only hence we can say java is a object
oriented technology.
Basic concepts of OOPs are:
1. Object 4. Polymorphism
2. Class 5. Abstraction
3. Inheritance 6.Encapsulation
3. Platform independent

The java is platform independent language.


The java program compiled in one operating system can be executed in any operating system
(using .class file) is known as platform independent.
Java code can be run on multiple platforms e.g. Windows, Linux, Sun Solaris, Mac/OS etc. Java code
is compiled by the compiler and converted into bytecode. This bytecode is a platform-independent
code because it can be run on multiple platforms i.e. Write Once and Run Anywhere(WORA).
4. Secured
Java is secured because:
• No explicit pointer
• Java Programs run inside virtual machine sandbox
• To provide implicit security Java provide one
component inside JVM called Security Manager.

• Classloader adds security by separating the package for the classes of the local file system
from those that are imported from network sources with predefined library in the form of
java.Security.package.
• Bytecode Verifier: checks the code fragments for illegal code that can violate access right to
objects.
• Security Manager: determines what resources a class can access such as reading and writing
to the local disk.
• These security are provided by java language. Some security can also be provided by
application developer through SSL, JAAS (Java Authentication and Authorization Services),
Cryptography etc.
5. Robust
JAVA is Robust because
• JAVA is having very good predefined Exception Handling mechanism.
• JAVA is having very good memory management system that is Dynamic Memory

Allocation (memory is allocated at runtime) and garbage collector.


6. Architecture-neutral
Java program compiled in one Architecture (hardware----RAM, Hard Disk) can run on any
hardware architecture(hardware) is called Architectural Neutral.
There are no implementation dependent features e.g. size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4
bytes of memory for 64-bit architecture. But in java, it occupies 4 bytes of memory for both
32 and 64 bit architectures.
7. Portable
In Java tech the applications are compiled and executed in any OS(operating system) and any
Architecture(hardware) hence we can say java is a portable language.
8. High-performance
If any technology having features like Robust, Security, Platform Independent, Dynamic and so
on then that technology is high performance.
9. Distributed
• We can create distributed applications in java. RMI and EJB are used for creating distributed
applications.
• We may access files by calling the methods from any machine on the internet.
• Java project code is distributed in multiple number of JVM’s.

10. Multi-threaded
• A thread is like a separate program, executing concurrently.
• Thread is a light weight process and a small task in large program.
• We can write Java programs that deal with many tasks at once by defining multiple threads. The
main advantage of multi-threading is that it doesn't occupy memory for each thread. It shares a
common memory area.
• Threads are important for multi-media, Web applications, gaming etc.
11. Dynamic
Java is dynamic technology it follows dynamic memory allocation(at runtime the memory is
allocated).
Implementation of java program
3. BASIC STRUCTURE OF A JAVA PROGRAM
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome To the World of Java");
}
}
 class keyword is used to declare a class in java.
 public keyword is an access modifier which represents visibility, it means it is visible to all.
 static is a keyword, if we declare any method as static, it is known as static method. The core advantage of
static method is that there is no need to create object to invoke the static method. The main method is
executed by the JVM, so it doesn't require to create object to invoke the main method. it saves memory.
 void is the return type of the method which doesn't return any value.
 main represents startup of the program.
 String[] args is used for command line argument.
 System.out.println() is used print statement.

File Name : Simple.java


Compile : javac Simple.java
Execute/Run : java Simple.java
Programming Assignment
a. Find the Greatest of 3 numbers
b. Arrange 3 numbers in ascending / descending order.
a=20,b=10,c=30
JVM At runtime? At runtime, following steps are
5.Java Byte Code performed:
At compile time?
At compile time, java file is compiled by Java
Compiler (It does not interact with OS) and
converts the java code into byte code.
• The output of a Java compiler is not executable
code. Rather, it is byte code.
• Byte code is a highly optimized set of
instructions designed to be executed by the Java
run-time system, which is called the Java Virtual
Machine (JVM).
Class loader: is the subsystem of JVM that is used to load class files.
Bytecode Verifier: checks the code fragments for illegal code that can violate access right to
objects.
Interpreter: read byte code stream then execute the instructions.

Once the run-time package exists for a given system, any Java program can run on it. Remember, although
the details of the JVM will differ from platform to platform, all understand the same Java byte code.
JVM Architecture

- JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java byte code can be executed.
- JVMs are available for many hardware and software platforms.
- Java is platform independent.

The JVM performs following operation:


o Loads code
o Verifies code
o Executes code
o Provides runtime environment
1) Classloader
Classloader is a subsystem of JVM that is used to load class files.
2) Class(Method) Area
Class(Method) Area stores per-class structures such as the runtime constant pool, class data,
field and method data, the code for methods.
3) Heap
It is the runtime data area in which objects are allocated.
4) Stack:
Java Stack stores frames. It holds local variables and partial results, and plays a part in method
invocation and return.
Each thread has a private JVM stack, created at the same time as thread.
A new frame is created each time a method is invoked. A frame is destroyed when its method
invocation completes.
5) Program Counter Register:
PC (program counter) register. It contains the address of the Java virtual machine instruction currently
being executed.
6) Native Method Stack:
It contains all the native methods used in the application.
7) Execution Engine It contains:
a) A virtual processor
b) Interpreter: Read byte code stream then execute the instructions.
c) Just-In-Time (JIT) compiler: It is used to improve the performance. JIT compiles parts of the byte code
that have similar functionality at the same time, and hence reduces the amount of time needed for
compilation. Here the term compiler Refers to a translator from the instruction set of a Java virtual
machine (JVM) to the instruction set of a specific CPU.
6. Data Types in Java
Data type specifies
1. Type of Value stored in a variable
2. Range of Values to a variable
3. Size of variable
In java, there are two types of data types:
1. Primitive data types
2. Non – Primitive Data Types
• Integer data types are signed, positive and negative values.
• Java does not support unsigned integers.
• To represent numeric values use byte, short, int, long.
• To represent decimal values use float and double.
• To represent character use char.
• To represent true or false use Boolean.
-Java Character System: Java Character set uses Unicode system.
-Unicode is a universal international standard character encoding that is capable of
representing most of the world's written languages.
Before Unicode, there were many language standards:
-ASCII (American Standard Code for Information Interchange) for the United States.
-In Unicode, character holds 2 byte, so java also uses 2 byte for characters.

 Java uses Unicode to represent characters.


 Unicode defines a fully international character set that can represent all of the
characters found in all human languages.
 It is a unification of dozens of character sets, such as Latin, Greek and many more.
 The range of a char is 0 to 65,535.
 There are no negative chars.
 The standard set of characters known as ASCII still ranges from 0 to 127 as always,
 Since Java is designed to allow programs to be written for worldwide use, it makes
sense that it would use Unicode to represent characters.
Using Java Scanner Class to read input
-Scanner is in the java.util package. So, use import java.util.Scanner;
-To create an object of Scanner class, we usually pass the predefined object System.in, which
represents the Standard input stream
-Constructing a Scanner object to read console input:
Scanner name = new Scanner(System.in);
-The Java Scanner class breaks the input into tokens using a delimiter that is whitespace by default.
Method Description
nextBoolean() Reads a boolean value from the user
nextByte() Reads a byte value from the user
nextDouble() Reads a double value from the user
nextFloat() Reads a float value from the user
nextInt() Reads a int value from the user
nextLine() Reads a String value from the user
nextLong() Reads a long value from the user
nextShort() Reads a short value from the user
//Program to find the average of a student in three subjects marks (Double).

import java.util.*;
public class Grade
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Entera the Marks in 3 Subjects");
double m1 = sc.nextDouble();
double m2 = sc.nextDouble();
double m3 = sc.nextDouble();
double avg = (m1+m2+m3)/3;
System.out.println("The average is "+avg);
}
}
7. Java Variables
Variable is a name given to memory location.
A Variable has
1. NAME (VALID IDENTIFIER)
2. VALUE
3. TYPE
4. SCOPE & LIFETIME

datatype var_name = [initial value]


int data=50; //Here data is variable

Types of Variable
There are three types of variables in java:
1) Local Variable 3) Static variable
The variables which are declare inside a method or a block or a The instance variable that is declared as static is called static
constructor is called local variables. variable. It cannot be local. Scope is within a class. (Stored in
The scope of local variables are inside a method or inside a Class Area of Memory).
constructor or inside a block. (Stored in Stack Memory) Able to access static variables within the class any number of
Ex: class Test { times.
public static void main(String[] args) {
int a=10; Ex: class Test {
int b=20; static int a=10, b=20;
System.out.println(a+b); public static void main(String[] args) {
}} System.out.println(a); //1-way(directly possible)
2) Instance Variable System.out.println(Test.a); //2-way(By using class name)
A variable which is declared inside the class but outside the Test t=new Test();
method is called instance variable. (Stored in Heap Memory). System.out.println(t.a); //3-way(By using reference variable)
Ex: class Test { System.out.println(a+b);
int a=10; }
int b=20; void add()
void add() { {
System.out.println(a+b); } System.out.printl(a+b);
public static void main(String[] args) { }
Test t=new Test(); 4) Reference variable
System.out.println(t.a+t.b); A variable that refers to object of a class. (Stored in Stack Area
t.add(); of Memory)
}}
8. Type Conversions and Type Casting
Type casting is a method or process that converts a data type into another data type in both ways manually and
automatically.
The automatic conversion is done by the compiler and manual conversion performed by the programmer.

Types of Type Casting


 Widening Type Casting
 Narrowing Type Casting

Widening Type Casting


Converting a lower data type into a higher one is called widening type casting.
It is also known as implicit conversion or casting down.
It is done automatically. It is safe because there is no chance to lose data.
It takes place when:
 Both data types must be compatible with each other.
 The target type must be larger than the source type.

byte -> short -> char -> int -> long -> float -> double

For example, the conversion between numeric data type to char or Boolean is not done automatically. Also, the
char and Boolean data types are not compatible with each other.
//example program for Widening Type Casting

public class WideningExample


{
public static void main(String[] args)
{
int x = 7;
//automatically converts the integer type into long type
long y = x;
//automatically converts the long type into float type
float z = y;
System.out.println("Before conversion, int value "+x);
System.out.println("After conversion, long value "+y);
System.out.println("After conversion, float value "+z);
}
}
Narrowing Type Casting
Converting a higher data type into a lower one is called narrowing type casting.
It is also known as explicit conversion or casting up.
It is done manually by the programmer. If we do not perform casting then the compiler
reports a compile-time error.
double -> float -> long -> int -> char -> short -> byte
public class NarrowingExample
{
public static void main(String args[])
{
double d = 166.66;
//converting double data type into long data type
long l = (long)d;
//converting long data type into int data type
int i = (int)l;
System.out.println("Before conversion: "+d);
//fractional part lost
System.out.println("After conversion into long type: "+l);
//fractional part lost
System.out.println("After conversion into int type: "+i);
}}
// Demonstrate Type Casting.
class Type2
{
public static void main(String args[])
{
byte b;
int i = 257;
double d = 323.142;
b = (byte) i;
System.out.println("i and b " + i + “ ” + b);
i = (int) d;
System.out.println("d and i " + d + “ ” + i);
b = (byte) d;
System.out.println("d and b " + d + “ ” + b);
}
}
COMMAND LINE ARGUMENTS
-The java command-line argument is an argument passed at the time of running the java program to
main method.
-The arguments passed from the console can be received in the java program and it can be used as an
input.
-So, it provides a convenient way to check the behavior of the program for the different values
-All command line arguments are of type String.

Simple example of command-line argument in java


public class Demo
{
public static void main(String args[])
{
System.out.println("First argument is: "+args[0]);
}
}
compile by > javac Demo.java
run by > java Demo Vardhaman
Output: First argument is: Vardhaman
Example of command-line argument that prints all the values
class Demo{
public static void main(String args[])
{
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
}
}
compile by > javac Demo.java
run by > java Demo hyd bag che

Output:
hyd
bag
che
9. Operators in Java
a) Arithmetic Operators (Arithmetic Operation)

public class OperatorDemo


{
public static void main(String args[])
{
int a=10,b=5;
System.out.println(a+b); //15
System.out.println(a-b); //5
System.out.println(a*b); //50
System.out.println(a/b); //2
System.out.println(a%3); //1
}
}
public class OperatorDemo
{
public static void main(String args[])
{
int x=10;
System.out.println(x++); //10 (11)
System.out.println(++x); //12
System.out.println(x--); //12 (11)
System.out.println(--x); //10
}
}
The outcome of these operations is a Boolean value.
int a = 4;
int b = 1;
boolean c = a < b;
System.out.println(“The C value is “ + c) //false
System.out.println(a==4) //True
System.out.println(a!=b) //True
System.out.println(a<=4) //True
Java logical Operators Example:
& , &&
public class OperDemo
{
public static void main(String
args[])
{
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a<c);
//false && true = false
System.out.println(a<b&a<c);
//false & true = false
}
}
Java logical Operators Example: & , && Java logical Operators Example: | , ||
public class OperDemo class OperDemo
{ {
public static void main(String args[]) public static void main(String args[])
{ {
int a=10; int a=10; int b=5; int c=20;
int b=5; System.out.println(a>b || a<c);
int c=20; //true || true = true
System.out.println(a<b && a++<c); System.out.println(a>b | a<c);
//false && true = false //true | true = true
System.out.println(a); System.out.println(a>b || a++<c);
//10 because second condition is not checked //true || true = true
System.out.println(a<b&a++<c); System.out.println(a);
//false && true = false //10 because second condition is not checked
System.out.println(a); System.out.println(a>b | a++<c);
//11 because second condition is checked //true | true = true
} System.out.println(a);
} //11 because second condition is checked
}
}
Java logical Operators Example: public class Operator
public class OperDemo {
{ public static void main(String args[])
public static void main(String args[]) {
{ boolean c=true;
int a=10; boolean d=false;
int b=5; System.out.println(!c); //false
int c=20; System.out.println(!d); //true
System.out.println( a>b ^ a<c); }
//Both are same result is - False }
System.out.println( a<b ^ a>c); public class OperatorExample
// Both are same result is - False {
System.out.println( a>b ^ a>c); public static void main(String args[])
// Both are different result is - True {
System.out.println( a<b ^ a<c); int a=20 , b=30;
// Both are Different result is - True int c= (a>b) ? a : b;
} System.out.println("The big is " + c);
} }
}
Java Unary Operator Example: ~ and ! public class Operator
{
public class Operator public static void main(String args[])
{ {
public static void main(String args[]) byte a=10;
{ byte b=8;
byte a=10; byte c;
byte b=-10; c = a | b;
System.out.println(~a); // -11 (one’s Complement) System.out.println(c);
System.out.println(~b); // 9 (one’s Complement) c = a & b;
} System.out.println(c);
} c = a ^ b;
System.out.println(c);
}
}
Java bitwise Operators Example: << , >>
public class Oper
{
public static void main(String args[])
{

byte a=10;
System.out.println(a<<2); //40
byte b=-15;
System.out.println(b<<3); //-120
byte c=10;
System.out.println(c>>2); //2
byte d=-15;
System.out.println(d>>1); //-8
}
}
Java bitwise Operators Example: >> , >>>
class Oper3 public class OperatorExample
{ {
public static void main(String args[]) public static void main(String args[])
{ {
//For positive number, >> and >>> works same int a=10;
System.out.println(20>>2); int b=20;
System.out.println(20>>>2); a+=4;//a=a+4 (a=10+4)
//For nagative number, >>> changes MSB to 0 b-=4;//b=b-4 (b=20-4)
System.out.println(-20>>2); System.out.println(a);
System.out.println(-20>>>2); System.out.println(b);
} }
} }
public class OperatorExample Java Assignment Operators Example
{ class OperatorExample
public static void main(String args[]) {
{ public static void main(String[] args)
System.out.println(10*10/5+3-1*4/2); //21 {
} } int a=10;
a+=3; //10+3
System.out.println(a);
a-=4; //13-4
System.out.println(a);
a*=2; //9*2
System.out.println(a);
a/=2; //18/2
System.out.println(a);
}
}
10. Control Statements
Conditional Statements
If Statement If else Statement
In Java if else statement is used to test the
The Java if statement is used to test
condition. If condition is true it executes true
the condition. If condition is true it
block, otherwise executes false block.
executes true block.
o if-else statement (two way)
o if statement (one way) if(condition)
if(condition) {
{ //code to be executed
//code to be executed }
} else
class Test { {
public static void main(String[] args) //code to be executed
{ }
int a=10;
if (a>5) Program to find whether given number is
System.out.println(“this is if block"); leap year or not.
}
}
nested if statement ( if inside another if-else-if ladder (Multi way selection)
if) if(condition1)
if(condition1) {
{ //code to be executed
if(condition2) }
{ else if(condition2)
//code to be executed {
} //code to be executed
//code to be executed }
} -----------------------
else
{
//code to be executed
}
Program to find ascending order of three Program to read a number and display day.
numbers
Switch Statement
switch statement is used to take multiple selections.
It is like if-else-if ladder statement.
Inside the switch It is possible to declare any number of cases but is possible to declare only
one default.
switch(expression)
{
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
// code to be executed if all cases are not matched;
}
***case values can be integer constant, character constant and string constant .
public class Example
{
public static void main(String[] args)
{
int number=20;
switch(number)
{
case 10: System.out.println("CSE");
break;
case 20: System.out.println("EEE");
break;
case 30: System.out.println("ECE");
break;
default: System.out.println("Invalid input");
Break;
}
}
}
Program to implement arithmetic operations using
switch statement.
Loop / Repetitive / Iterative Statements
if we want to execute group of statements repeatedly
or more number of times then we should go for class Test
iteration statements. {
Three types of iteration statements present in the public static void main (String[] args)
java language {
1) For int i=0;
2) while while (i<10)
3) do-while {
System.out.println(“CSM”);
while Loop i++;
The Java while loop is used to iterate a part of the }
program several times. If the number of iteration is }
not fixed, it is recommended to use while loop. }
Syntax:
while(condition)
{
//code to be executed
}
do-while Loop
• If we want to execute the loop body at least one time them we should go for do-while
statement.
• In the do-while first body will be executed then only condition will be checked.
• In the do-while the while must be ends with semicolon otherwise we are getting compilation
error.
• do is taking the body and while is taking the condition and the condition must be Boolean
condition. class Test
{
Syntax:
public static void main(String[] args)
do
{
{
int i=0;
//code to be executed do
}while(condition); {
System.out.println(“CSM");
i++;
}while (i<10);
}
}
for Loop
The Java for loop is used to iterate a part of the program several times.
If the number of iteration is fixed, it is recommended to use for loop.

Parts of for loop


Initialization
Condition
increment/decrement
Example:
Syntax: class Test
for(initialization;condition;incr/decr) {
{ public static void main(String[] args)
//code to be executed {
} for (int i=0;i<10;i++)
{
System.out.println(“CSM");
}
}
}
Jump Statements
break Statement
• The Java break is used to break loop or switch statement. It breaks the current flow of
the program at specified condition.
• When a break statement is encountered inside a loop, the loop is terminated and
program control resumes at the next statement following the loop.
• In case of inner loop, it breaks only inner loop.

example
for(int i=1;i<=10;i++)
{
if(i==5)
{
break;
}
}
System.out.println(i);
Continue Statement
• The Java continue statement is used to continue loop.
• We might want to continue running the loop but stop processing the remainder of the code in
its body for this particular iteration.
• It continues the current flow of the program and skips the remaining code at specified
condition.
• In case of inner loop, it continues only inner loop.

Example:
for(int i=1;i<=6;i++)
{
if(i==3)
{
continue;
}
System.out.println(i);
}
return Statement

• The return statement is used to explicitly public class Demo


return from a method. That is, it causes {
program control to transfer back to the caller public static void main(String[] args)
of the method.
{
• At any time in a method the return statement
int res;
can be used to cause execution to branch
back to the caller of the method. res = add(20,30);
• Thus, the return statement immediately System.out.println("The result is "+res);
terminates the method in which it is }
executed. public static int add(int a , int b)
{
return(a+b);
}
}
Problem Solving Assignment:

1. Write a Java Program to sort elements in ascending order


2. Write a Java Program to list the common elements in two arrays.
3. Program to find the sum of the digits of a number.
4. Program to display a number in name. [123 -> one two three]
5. Program to find factorial of a number using do-while.
6. Program to check a number is palindrome or not.

You might also like