SlideShare a Scribd company logo
Java Programming basics http://ir.linkedin.com/in/ghorbanihamid
١
Java – Overview
- was created in 1991 by (James Gosling, Mike Sheridan, and Patrick Naughton)
- developed and Published by Sun Microsystems which in 1995 as Java 1.0
- Initially called Oak, its name was changed to Java because there was
already a language called Oak.
Editions:
Java ME (Micro Edition): targeting environments with limited resources (mobile
devices, micro-controllers, sensors, gateways, TV set-top boxes, printers)
Java SE (Standard Edition): core Java programming platform
targeting desktop and server environments It contains all of the libraries and APIs that
any Java programmer should learn (java.lang, java.io, java.math, java.net, java.util,
etc...).
Java EE (Enterprise Edition):
targeting large scale softwares (Network or Internet environments)
Versions:
 JDK 1.0 (January 23, 1996)[38]
 JDK 1.1 (February 19, 1997)
 J2SE 1.2 (December 8, 1998)
 J2SE 1.3 (May 8, 2000)
 J2SE 1.4 (February 6, 2002)
 J2SE 5.0 (September 30, 2004)
 Java SE 6 (December 11, 2006)
 Java SE 7 (July 28, 2011)
 Java SE 8 (March 18, 2014)
Note: As of 2015, only Java 8 is officially supported
Java Programming basics http://ir.linkedin.com/in/ghorbanihamid
٢
Principles:
guaranteed to be Write Once, Run Anywhere.
Object Oriented: In Java, everything is an Object.
Secure: With Java's secure feature it enables to develop virus-free, tamper-
free systems.
Portable: Compiler in Java is written in ANSI C with a clean portability
boundary, which is a POSIX subset.
Platform Independent: Unlike many other programming languages including C
and C++, when Java is compiled, it is not compiled into platform specific machine, rather
into platform independent byte code. This byte code is distributed over the web and
interpreted by the Virtual Machine (JVM) on whichever platform it is being run on.
JVM (Java Virtual Machine): bytecode interpreter
JVM is a virtual machine which work on top of your operating system to provide a recommended
environment for your compiled Java code. JVM only works with bytecode. Hence you need to
compile your Java application(.java) so that it can be converted to bytecode format (.class file). Which
then will be used by JVM to run application. JVM only provide the environment It needs the Java code
library to run applications.
Java Programming basics http://ir.linkedin.com/in/ghorbanihamid
٣
JDK (Java Development Kit)
JDK contains everything that will be required to develop and run Java application.
JDK = JRE + development tools
JRE (Java Run time Environment)
JRE contains everything required to run Java application which has already been compiled. It
doesn’t contain the code library required to develop Java application.
JRE = JVM + Java Packages Classes (like util, math, lang, awt, swing etc) + runtime libraries.
The programming structure:
Sun Micro System has prescribed the following structure for developing java application.
Java Programming basics http://ir.linkedin.com/in/ghorbanihamid
۴
Package: Package is a collection of classes, interfaces and sub-packages. A sub package contains
collection of classes, interfaces and sub-sub packages etc. java.lang.*; package is imported by default and
this package is known as default package.
Class: In Java, every line of code that can actually run needs to be inside a class. Notice that when we
declare a public class, we must declare it inside a file with the same name, otherwise we'll get an error
when compiling.
Methods: A method is a set of code which is referred to by name. When that name is encountered in a
program, the execution of the program branches to the body of that method. When the method is
finished, execution returns to the area of the program code from which it was called, and the program
continues on to the next line of code.
Language basics:
Case Sensitivity: Java is case sensitive, which means identifier Hello and hello would have
different meaning in Java.
Class Names: For all class names the first letter should be in Upper Case. If several words are used to
form a name of the class, each inner word's first letter should be in Upper Case.
Example: class MyFirstJavaClass
Method Names: All method names should start with a Lower Case letter. If several words are used
to form the name of the method, then each inner word's first letter should be in Upper Case.
Example: public void myMethodName()
Program File Name: Name of the program file should exactly match the class name. When saving
the file, you should save it using the class name (Remember Java is case sensitive) and append '.java' to
the end of the name (if the file name and the class name do not match, your program will not compile).
Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as
'MyFirstJavaProgram.java'
public static void main(String args[]): Java program processing starts from the main() method
which is a mandatory part of every Java program.
Java Programming basics http://ir.linkedin.com/in/ghorbanihamid
۵
Java Data types:
There are two data types available in Java:
- Primitive Datatypes: There are 8 basic data types available within the Java language.
Name Type
Minimum
value
Maximum value Default
value
byte number, 1 byte -128 , 128 0
short number, 2 bytes -32,768 32,767 0
int number, 4 bytes - 2,147,483,648
(-2^31)
2,147,483,647 (2^31 -1) 0
long number, 8 bytes -2^63 2^63 -1 0L
float float number, 4 bytes 1.4E^-45 3.4028235E^38 0.0f
double float number, 8 bytes 4.9E^-324 1.7976931348623157E^308 0.0d
char a character, 2 bytes 'u0000' (or 0) 'uffff' (or 65,535) 'u0000'
boolean true or false, 1 bit false
*** Note: To declare and assign a number use the following syntax:
Variable_Type variable_Name;
Example:
int a, b, c; // Declares three ints, a, b, and c.
int a = 10, b = 10; // Example of initialization
byte B = 22; // initializes a byte type variable B.
double pi = 3.14159; // declares and assigns a value of PI.
char a = 'a'; // the char variable a is initialized with value 'a'
- Reference/Object Datatypes : A reference type is a data type that’s based on a class, a
reference type is an instantiable class
Example:
Person person = new Person();
Java Programming basics http://ir.linkedin.com/in/ghorbanihamid
۶
Java Variables
To declare and assign a number use the following syntax:
Variable_Type variable_Name;
***Following are the types of variables in Java:
- Local Variables
- Class Variables (Static Variables)
- Instance Variables (Non-static Variables)
Local Variables: Local variables are declared in methods, constructors, or blocks and are visible
only within the declared method, constructor, or block.
Instance Variables: Instance variables belong to the instance of a class(an object) and every
instance of that class (object) has it's own copy of that variable.
Example:
public class Product {
public int barcode; // an instance variable
}
public class MyFirstJavaProgram {
public static void main(String[] args) {
Product product1 = new Product();
product1.barcode = 123456;
System.out.println(product1.barcode);
}
}
Class Variables: Class variables also known as static variables are declared with the
static keyword in a class, but outside a method, constructor or a block. class variable is
a variable defined in a class of which a single copy exists, regardless of how many instances
of the class exist.
public class MyFirstJavaProgram {
static int barcode;
}
Java Programming basics http://ir.linkedin.com/in/ghorbanihamid
٧
Java Modifiers:
Like other languages, it is possible to modify classes, methods, etc., by using modifiers. There are
two categories of modifiers:
Access Modifiers: default, public , protected, private
Non-access Modifiers: final, abstract, strictfp
if-else statement:
An if statement can be followed by an optional else statement, which executes when the
Boolean expression is false.
if( x < 20 ) {
System.out.print("This is if statement");
}else {
System.out.print("This is else statement");
}
while-loop
A while loop statement in Java programming language repeatedly executes a target
statement as long as a given condition is true.
int x = 0;
while( x < 20 ) {
System.out.print("This is while statement : " + x);
X++;
}
do-while-loop
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed
to execute at least one time.
int x = 0;
while( x < 20 ) {
System.out.print("This is while statement : " + x);
X++;
}
Java Programming basics http://ir.linkedin.com/in/ghorbanihamid
٨
for-loop
A for loop is a repetition control structure that allows you to efficiently write a loop that
needs to be executed a specific number of times.
for( int i = 0; i < 20; i++ ) {
System.out.print("This is for-loop statement : " + i);
}
For-each loop
The for-each loop(Advanced or Enhanced For loop) introduced in Java5. It is mainly
used to traverse array or collection elements. The advantage of for-each loop is that it
eliminates the possibility of bugs and makes the code more readable.
for(data_type variable : array | collection){ …. }
Example 1:
int arr[]={12,13,14,44};
for( int i:arr) {
System.out.print("This is for- each loop statement : " + i);
}
Example 2:
ArrayList<String> list=new ArrayList<String>();
list.add("vimal");
list.add("sonoo");
list.add("ratan");
for(String s:list){
System.out.println(s);
}
Java Programming basics http://ir.linkedin.com/in/ghorbanihamid
٩
Branching Statements
Java offers three branching statements:
 break
 continue
 return
Break
This statement can be used to terminate a switch, for, while, or do-while loop
for(int i=1;i<=10;i++){
if(i==5){
break;
}
System.out.println(i);
}
Continue
The continue keyword causes the loop to immediately jump to the next iteration of the loop.
for(int i=1;i<=3;i++){
for(int j=1;j<=3;j++){
if(i==2&&j==2){
continue;
}
System.out.println(i+" "+j);
}
}
return
used to exit from the current method.
public static int minFunction(int n1, int n2) {
int min;
min = n2;
return min;
}
Java Programming basics http://ir.linkedin.com/in/ghorbanihamid
١
Switch statement
The Java switch statement executes one statement from multiple conditions. It is like if-
else-if ladder statement.
Example:
public class SwitchExample {
public static void main(String[] args) {
int number=20;
switch(number){
case 10: System.out.println("10");break;
case 20: System.out.println("20");break;
case 30: System.out.println("30");break;
default:System.out.println("Not in 10, 20 or 30");
}
}
}
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);
}
}
Java Programming basics http://ir.linkedin.com/in/ghorbanihamid
١
Arrays
Java arrays, is a data structure 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.
Syntax:
1)
dataType[] arrayName; or
dataType arrayName[];
Example:
// declaration
Int[] myList;
// instantiate object
myList = new int[10];
2)
dataType[] arrayName = new datatype[size];
Example:
double[] myList = new double[10];
Array initialization:
1) after declaration:
 a[0]=10;
 a[1]=20;
 a[2]=70;
 a[3]=40;
2) with declaration:
int[] arr = {1, 2, 3, 4, 5};
String[] days = { “Mon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”,“Sun”};
Java Programming basics http://ir.linkedin.com/in/ghorbanihamid
١
Note1: The elements of an array have indexes from 0 to n-1.
Note that there is no array element arr[n]! This will result in an
"array-index-out-ofbounds" exception.
Note2: You cannot resize an array.
public class TestArray {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (int i = 0; i < myList.length; i++) {
System.out.println(myList[i] + " ");
}
// Summing all elements
double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
System.out.println("Total is " + total);
// Finding the largest element
double max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}
}
Java Programming basics http://ir.linkedin.com/in/ghorbanihamid
١
Copying Array:
1) reference Copy: use the assignment statement (=)
list2 = list1;
2) Value Copy:
2_1) write a loop to copy every element:
2_2) use arraycopy method: it is in the java.lang.System class
arraycopy(sourceArray, srcPos, targetArray, tarPos, length);
 srcPos and tarPos indicate the starting positions in sourceArray and
targetArray, respectively.
 The number of elements copied from sourceArray to targetArray is
indicated by length.
arraycopy(sourceArray, 0, targetArray, 0, sourceArray.length);
Java Programming basics http://ir.linkedin.com/in/ghorbanihamid
١
Multidimensional Arrays:
1) int[][] arr = new int[3][3]; //3 row and 3 column
2) // declaring and initializing 2D array
int arr[][] = {{1,2,3},{2,4,5},{4,4,5}};
Example:
// String array 4 rows x 2 columns
String[][] dogs = {
{ "terry", "brown" },
{ "Kristin", "white" },
{ "toby", "gray"},
{ "fido", "black"}
};
Example:
// character array 8 x 16 x 24
char[][][] threeD = new char[8][16][24];
Java Programming basics http://ir.linkedin.com/in/ghorbanihamid
١
Lengths of Two-Dimensional Arrays
x = new int[3][4];
x.length is ?
Traversing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
Output:1 2 3
2 4 5
4 4 5
Java Programming basics http://ir.linkedin.com/in/ghorbanihamid
١
The Array Class
The java.util.Arrays class contains various static methods for sorting and searching arrays,
comparing arrays, and filling array elements.
Sort:
This method sorts the specified array of ints into ascending numerical order.
BinarySearch:
searches the specified array of ints for the specified value using the binary search
algorithm.The array must be sorted before making this call.
import java.util.Arrays;
public class ArrayDemo {
public static void main(String[] args) {
// initializing unsorted int array
int iArr[] = {2, 1, 9, 6, 4};
// sorting array
Arrays.sort(iArr);
for (int number : iArr) {
System.out.println("Number = " + number);
}
int searchVal = 12;
int retVal = Arrays.binarySearch(intArr,searchVal);
System.out.println("The index of element 12 is : " + retVal);
}
}
Java Programming basics http://ir.linkedin.com/in/ghorbanihamid
١
equals: You can use the equals method to check whether two arrays are equal.
import java.util.Arrays;
public class ArrayDemo {
public static void main(String[] args) {
// initiliazing three object arrays
Object[] arr1 = new Object[] { 1, 123 };
Object[] arr2 = new Object[] { 1, 123, 22, 4 };
Object[] arr3 = new Object[] { 1, 123 };
// comparing arr1 and arr2
boolean retval=Arrays.equals(arr1, arr2);
System.out.println("arr1 and arr2 equal: " + retval);
// comparing arr1 and arr3
boolean retval2=Arrays.equals(arr1, arr3);
System.out.println("arr1 and arr3 equal: " + retval2);
}
}
fill: You can use the fill method to fill in the whole array or part of the array.
import java.util.Arrays;
public class ArrayDemo {
public static void main(String[] args) {
// initializing int array
int arr[] = new int[] {1, 6, 3, 2, 9};
// using fill for placing 18
Arrays.fill(arr, 18);
for (int value : arr) {
System.out.println("Value = " + value);
}
}
}

More Related Content

PDF
Next.js Introduction
PDF
Angular directives and pipes
PPTX
Selenium WebDriver training
PPTX
Test Cases Vs Test Scenarios
PPTX
Properties and indexers in C#
PPT
Java Programming for Designers
PPTX
Why TypeScript?
PDF
Next.js Introduction
Angular directives and pipes
Selenium WebDriver training
Test Cases Vs Test Scenarios
Properties and indexers in C#
Java Programming for Designers
Why TypeScript?

What's hot (20)

PPT
TypeScript Presentation
PDF
TypeScript: coding JavaScript without the pain
PPTX
PPTX
Introduction to Bdd and cucumber
PDF
Refactoring: A First Example - Martin Fowler’s First Example of Refactoring, ...
PDF
An introduction to Google test framework
PDF
What is Regression Testing? | Edureka
PDF
TypeScript Introduction
PDF
JavaScript - Chapter 15 - Debugging Techniques
PPTX
Javascript Design Patterns
PPTX
Object Oriented Programming In JavaScript
PPTX
Typescript ppt
PDF
Test and Behaviour Driven Development (TDD/BDD)
PDF
Java 17
PDF
JavaScript - Chapter 7 - Advanced Functions
PPTX
TypeScript intro
PPSX
Principles of Software testing
PPTX
Bug life cycle
PDF
Integration test
PPTX
Sanity testing and smoke testing
TypeScript Presentation
TypeScript: coding JavaScript without the pain
Introduction to Bdd and cucumber
Refactoring: A First Example - Martin Fowler’s First Example of Refactoring, ...
An introduction to Google test framework
What is Regression Testing? | Edureka
TypeScript Introduction
JavaScript - Chapter 15 - Debugging Techniques
Javascript Design Patterns
Object Oriented Programming In JavaScript
Typescript ppt
Test and Behaviour Driven Development (TDD/BDD)
Java 17
JavaScript - Chapter 7 - Advanced Functions
TypeScript intro
Principles of Software testing
Bug life cycle
Integration test
Sanity testing and smoke testing
Ad

Similar to Java programming basics (20)

PDF
Java programming material for beginners by Nithin, VVCE, Mysuru
PPTX
Core java &collections
PPTX
Core java1
PPTX
Core java
PPTX
Introduction-to-Java-Programming-Language (1).pptx
PPTX
PPT
Chapter 1 java
PPT
Jacarashed-1746968053-300050282-Java.ppt
PDF
java notes.pdf
PPTX
object oriented programming unit one ppt
PPTX
Java Notes
PPTX
Java Notes by C. Sreedhar, GPREC
PPTX
What is Java, JDK, JVM, Introduction to Java.pptx
PPT
Comp102 lec 3
ODP
Introduction To Java.
PPTX
LECTURE 2 -Object oriented Java Basics.pptx
PPTX
INDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptx
PPT
Learning Java 1 – Introduction
PPTX
PPTX
Introduction to Java.pptx sjskmdkdmdkdmdkdkd
Java programming material for beginners by Nithin, VVCE, Mysuru
Core java &collections
Core java1
Core java
Introduction-to-Java-Programming-Language (1).pptx
Chapter 1 java
Jacarashed-1746968053-300050282-Java.ppt
java notes.pdf
object oriented programming unit one ppt
Java Notes
Java Notes by C. Sreedhar, GPREC
What is Java, JDK, JVM, Introduction to Java.pptx
Comp102 lec 3
Introduction To Java.
LECTURE 2 -Object oriented Java Basics.pptx
INDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptx
Learning Java 1 – Introduction
Introduction to Java.pptx sjskmdkdmdkdmdkdkd
Ad

More from Hamid Ghorbani (16)

PDF
Spring aop
PDF
Spring boot jpa
PDF
Spring mvc
PDF
Payment Tokenization
PDF
Reactjs Basics
PDF
Rest web service
PDF
Java inheritance
PDF
Java I/o streams
PDF
Java Threads
PDF
Java Reflection
PDF
Java Generics
PDF
Java collections
PDF
IBM Integeration Bus(IIB) Fundamentals
PDF
ESB Overview
PDF
Spring security configuration
PDF
SOA & ESB in banking systems(Persian language)
Spring aop
Spring boot jpa
Spring mvc
Payment Tokenization
Reactjs Basics
Rest web service
Java inheritance
Java I/o streams
Java Threads
Java Reflection
Java Generics
Java collections
IBM Integeration Bus(IIB) Fundamentals
ESB Overview
Spring security configuration
SOA & ESB in banking systems(Persian language)

Recently uploaded (20)

PDF
AI in Product Development-omnex systems
PPTX
ISO 45001 Occupational Health and Safety Management System
PDF
PTS Company Brochure 2025 (1).pdf.......
PPT
Introduction Database Management System for Course Database
PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PPTX
history of c programming in notes for students .pptx
PDF
Understanding Forklifts - TECH EHS Solution
PDF
System and Network Administration Chapter 2
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PDF
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
PDF
Softaken Excel to vCard Converter Software.pdf
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PPTX
CHAPTER 2 - PM Management and IT Context
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PPTX
ManageIQ - Sprint 268 Review - Slide Deck
AI in Product Development-omnex systems
ISO 45001 Occupational Health and Safety Management System
PTS Company Brochure 2025 (1).pdf.......
Introduction Database Management System for Course Database
Navsoft: AI-Powered Business Solutions & Custom Software Development
history of c programming in notes for students .pptx
Understanding Forklifts - TECH EHS Solution
System and Network Administration Chapter 2
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
Upgrade and Innovation Strategies for SAP ERP Customers
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
How to Choose the Right IT Partner for Your Business in Malaysia
Design an Analysis of Algorithms I-SECS-1021-03
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
Softaken Excel to vCard Converter Software.pdf
Design an Analysis of Algorithms II-SECS-1021-03
CHAPTER 2 - PM Management and IT Context
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
ManageIQ - Sprint 268 Review - Slide Deck

Java programming basics

  • 1. Java Programming basics http://ir.linkedin.com/in/ghorbanihamid ١ Java – Overview - was created in 1991 by (James Gosling, Mike Sheridan, and Patrick Naughton) - developed and Published by Sun Microsystems which in 1995 as Java 1.0 - Initially called Oak, its name was changed to Java because there was already a language called Oak. Editions: Java ME (Micro Edition): targeting environments with limited resources (mobile devices, micro-controllers, sensors, gateways, TV set-top boxes, printers) Java SE (Standard Edition): core Java programming platform targeting desktop and server environments It contains all of the libraries and APIs that any Java programmer should learn (java.lang, java.io, java.math, java.net, java.util, etc...). Java EE (Enterprise Edition): targeting large scale softwares (Network or Internet environments) Versions:  JDK 1.0 (January 23, 1996)[38]  JDK 1.1 (February 19, 1997)  J2SE 1.2 (December 8, 1998)  J2SE 1.3 (May 8, 2000)  J2SE 1.4 (February 6, 2002)  J2SE 5.0 (September 30, 2004)  Java SE 6 (December 11, 2006)  Java SE 7 (July 28, 2011)  Java SE 8 (March 18, 2014) Note: As of 2015, only Java 8 is officially supported
  • 2. Java Programming basics http://ir.linkedin.com/in/ghorbanihamid ٢ Principles: guaranteed to be Write Once, Run Anywhere. Object Oriented: In Java, everything is an Object. Secure: With Java's secure feature it enables to develop virus-free, tamper- free systems. Portable: Compiler in Java is written in ANSI C with a clean portability boundary, which is a POSIX subset. Platform Independent: Unlike many other programming languages including C and C++, when Java is compiled, it is not compiled into platform specific machine, rather into platform independent byte code. This byte code is distributed over the web and interpreted by the Virtual Machine (JVM) on whichever platform it is being run on. JVM (Java Virtual Machine): bytecode interpreter JVM is a virtual machine which work on top of your operating system to provide a recommended environment for your compiled Java code. JVM only works with bytecode. Hence you need to compile your Java application(.java) so that it can be converted to bytecode format (.class file). Which then will be used by JVM to run application. JVM only provide the environment It needs the Java code library to run applications.
  • 3. Java Programming basics http://ir.linkedin.com/in/ghorbanihamid ٣ JDK (Java Development Kit) JDK contains everything that will be required to develop and run Java application. JDK = JRE + development tools JRE (Java Run time Environment) JRE contains everything required to run Java application which has already been compiled. It doesn’t contain the code library required to develop Java application. JRE = JVM + Java Packages Classes (like util, math, lang, awt, swing etc) + runtime libraries. The programming structure: Sun Micro System has prescribed the following structure for developing java application.
  • 4. Java Programming basics http://ir.linkedin.com/in/ghorbanihamid ۴ Package: Package is a collection of classes, interfaces and sub-packages. A sub package contains collection of classes, interfaces and sub-sub packages etc. java.lang.*; package is imported by default and this package is known as default package. Class: In Java, every line of code that can actually run needs to be inside a class. Notice that when we declare a public class, we must declare it inside a file with the same name, otherwise we'll get an error when compiling. Methods: A method is a set of code which is referred to by name. When that name is encountered in a program, the execution of the program branches to the body of that method. When the method is finished, execution returns to the area of the program code from which it was called, and the program continues on to the next line of code. Language basics: Case Sensitivity: Java is case sensitive, which means identifier Hello and hello would have different meaning in Java. Class Names: For all class names the first letter should be in Upper Case. If several words are used to form a name of the class, each inner word's first letter should be in Upper Case. Example: class MyFirstJavaClass Method Names: All method names should start with a Lower Case letter. If several words are used to form the name of the method, then each inner word's first letter should be in Upper Case. Example: public void myMethodName() Program File Name: Name of the program file should exactly match the class name. When saving the file, you should save it using the class name (Remember Java is case sensitive) and append '.java' to the end of the name (if the file name and the class name do not match, your program will not compile). Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as 'MyFirstJavaProgram.java' public static void main(String args[]): Java program processing starts from the main() method which is a mandatory part of every Java program.
  • 5. Java Programming basics http://ir.linkedin.com/in/ghorbanihamid ۵ Java Data types: There are two data types available in Java: - Primitive Datatypes: There are 8 basic data types available within the Java language. Name Type Minimum value Maximum value Default value byte number, 1 byte -128 , 128 0 short number, 2 bytes -32,768 32,767 0 int number, 4 bytes - 2,147,483,648 (-2^31) 2,147,483,647 (2^31 -1) 0 long number, 8 bytes -2^63 2^63 -1 0L float float number, 4 bytes 1.4E^-45 3.4028235E^38 0.0f double float number, 8 bytes 4.9E^-324 1.7976931348623157E^308 0.0d char a character, 2 bytes 'u0000' (or 0) 'uffff' (or 65,535) 'u0000' boolean true or false, 1 bit false *** Note: To declare and assign a number use the following syntax: Variable_Type variable_Name; Example: int a, b, c; // Declares three ints, a, b, and c. int a = 10, b = 10; // Example of initialization byte B = 22; // initializes a byte type variable B. double pi = 3.14159; // declares and assigns a value of PI. char a = 'a'; // the char variable a is initialized with value 'a' - Reference/Object Datatypes : A reference type is a data type that’s based on a class, a reference type is an instantiable class Example: Person person = new Person();
  • 6. Java Programming basics http://ir.linkedin.com/in/ghorbanihamid ۶ Java Variables To declare and assign a number use the following syntax: Variable_Type variable_Name; ***Following are the types of variables in Java: - Local Variables - Class Variables (Static Variables) - Instance Variables (Non-static Variables) Local Variables: Local variables are declared in methods, constructors, or blocks and are visible only within the declared method, constructor, or block. Instance Variables: Instance variables belong to the instance of a class(an object) and every instance of that class (object) has it's own copy of that variable. Example: public class Product { public int barcode; // an instance variable } public class MyFirstJavaProgram { public static void main(String[] args) { Product product1 = new Product(); product1.barcode = 123456; System.out.println(product1.barcode); } } Class Variables: Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block. class variable is a variable defined in a class of which a single copy exists, regardless of how many instances of the class exist. public class MyFirstJavaProgram { static int barcode; }
  • 7. Java Programming basics http://ir.linkedin.com/in/ghorbanihamid ٧ Java Modifiers: Like other languages, it is possible to modify classes, methods, etc., by using modifiers. There are two categories of modifiers: Access Modifiers: default, public , protected, private Non-access Modifiers: final, abstract, strictfp if-else statement: An if statement can be followed by an optional else statement, which executes when the Boolean expression is false. if( x < 20 ) { System.out.print("This is if statement"); }else { System.out.print("This is else statement"); } while-loop A while loop statement in Java programming language repeatedly executes a target statement as long as a given condition is true. int x = 0; while( x < 20 ) { System.out.print("This is while statement : " + x); X++; } do-while-loop A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time. int x = 0; while( x < 20 ) { System.out.print("This is while statement : " + x); X++; }
  • 8. Java Programming basics http://ir.linkedin.com/in/ghorbanihamid ٨ for-loop A for loop is a repetition control structure that allows you to efficiently write a loop that needs to be executed a specific number of times. for( int i = 0; i < 20; i++ ) { System.out.print("This is for-loop statement : " + i); } For-each loop The for-each loop(Advanced or Enhanced For loop) introduced in Java5. It is mainly used to traverse array or collection elements. The advantage of for-each loop is that it eliminates the possibility of bugs and makes the code more readable. for(data_type variable : array | collection){ …. } Example 1: int arr[]={12,13,14,44}; for( int i:arr) { System.out.print("This is for- each loop statement : " + i); } Example 2: ArrayList<String> list=new ArrayList<String>(); list.add("vimal"); list.add("sonoo"); list.add("ratan"); for(String s:list){ System.out.println(s); }
  • 9. Java Programming basics http://ir.linkedin.com/in/ghorbanihamid ٩ Branching Statements Java offers three branching statements:  break  continue  return Break This statement can be used to terminate a switch, for, while, or do-while loop for(int i=1;i<=10;i++){ if(i==5){ break; } System.out.println(i); } Continue The continue keyword causes the loop to immediately jump to the next iteration of the loop. for(int i=1;i<=3;i++){ for(int j=1;j<=3;j++){ if(i==2&&j==2){ continue; } System.out.println(i+" "+j); } } return used to exit from the current method. public static int minFunction(int n1, int n2) { int min; min = n2; return min; }
  • 10. Java Programming basics http://ir.linkedin.com/in/ghorbanihamid ١ Switch statement The Java switch statement executes one statement from multiple conditions. It is like if- else-if ladder statement. Example: public class SwitchExample { public static void main(String[] args) { int number=20; switch(number){ case 10: System.out.println("10");break; case 20: System.out.println("20");break; case 30: System.out.println("30");break; default:System.out.println("Not in 10, 20 or 30"); } } } 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); } }
  • 11. Java Programming basics http://ir.linkedin.com/in/ghorbanihamid ١ Arrays Java arrays, is a data structure 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. Syntax: 1) dataType[] arrayName; or dataType arrayName[]; Example: // declaration Int[] myList; // instantiate object myList = new int[10]; 2) dataType[] arrayName = new datatype[size]; Example: double[] myList = new double[10]; Array initialization: 1) after declaration:  a[0]=10;  a[1]=20;  a[2]=70;  a[3]=40; 2) with declaration: int[] arr = {1, 2, 3, 4, 5}; String[] days = { “Mon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”,“Sun”};
  • 12. Java Programming basics http://ir.linkedin.com/in/ghorbanihamid ١ Note1: The elements of an array have indexes from 0 to n-1. Note that there is no array element arr[n]! This will result in an "array-index-out-ofbounds" exception. Note2: You cannot resize an array. public class TestArray { public static void main(String[] args) { double[] myList = {1.9, 2.9, 3.4, 3.5}; // Print all the array elements for (int i = 0; i < myList.length; i++) { System.out.println(myList[i] + " "); } // Summing all elements double total = 0; for (int i = 0; i < myList.length; i++) { total += myList[i]; } System.out.println("Total is " + total); // Finding the largest element double max = myList[0]; for (int i = 1; i < myList.length; i++) { if (myList[i] > max) max = myList[i]; } System.out.println("Max is " + max); } }
  • 13. Java Programming basics http://ir.linkedin.com/in/ghorbanihamid ١ Copying Array: 1) reference Copy: use the assignment statement (=) list2 = list1; 2) Value Copy: 2_1) write a loop to copy every element: 2_2) use arraycopy method: it is in the java.lang.System class arraycopy(sourceArray, srcPos, targetArray, tarPos, length);  srcPos and tarPos indicate the starting positions in sourceArray and targetArray, respectively.  The number of elements copied from sourceArray to targetArray is indicated by length. arraycopy(sourceArray, 0, targetArray, 0, sourceArray.length);
  • 14. Java Programming basics http://ir.linkedin.com/in/ghorbanihamid ١ Multidimensional Arrays: 1) int[][] arr = new int[3][3]; //3 row and 3 column 2) // declaring and initializing 2D array int arr[][] = {{1,2,3},{2,4,5},{4,4,5}}; Example: // String array 4 rows x 2 columns String[][] dogs = { { "terry", "brown" }, { "Kristin", "white" }, { "toby", "gray"}, { "fido", "black"} }; Example: // character array 8 x 16 x 24 char[][][] threeD = new char[8][16][24];
  • 15. Java Programming basics http://ir.linkedin.com/in/ghorbanihamid ١ Lengths of Two-Dimensional Arrays x = new int[3][4]; x.length is ? Traversing 2D array for(int i=0;i<3;i++){ for(int j=0;j<3;j++){ System.out.print(arr[i][j]+" "); } System.out.println(); } Output:1 2 3 2 4 5 4 4 5
  • 16. Java Programming basics http://ir.linkedin.com/in/ghorbanihamid ١ The Array Class The java.util.Arrays class contains various static methods for sorting and searching arrays, comparing arrays, and filling array elements. Sort: This method sorts the specified array of ints into ascending numerical order. BinarySearch: searches the specified array of ints for the specified value using the binary search algorithm.The array must be sorted before making this call. import java.util.Arrays; public class ArrayDemo { public static void main(String[] args) { // initializing unsorted int array int iArr[] = {2, 1, 9, 6, 4}; // sorting array Arrays.sort(iArr); for (int number : iArr) { System.out.println("Number = " + number); } int searchVal = 12; int retVal = Arrays.binarySearch(intArr,searchVal); System.out.println("The index of element 12 is : " + retVal); } }
  • 17. Java Programming basics http://ir.linkedin.com/in/ghorbanihamid ١ equals: You can use the equals method to check whether two arrays are equal. import java.util.Arrays; public class ArrayDemo { public static void main(String[] args) { // initiliazing three object arrays Object[] arr1 = new Object[] { 1, 123 }; Object[] arr2 = new Object[] { 1, 123, 22, 4 }; Object[] arr3 = new Object[] { 1, 123 }; // comparing arr1 and arr2 boolean retval=Arrays.equals(arr1, arr2); System.out.println("arr1 and arr2 equal: " + retval); // comparing arr1 and arr3 boolean retval2=Arrays.equals(arr1, arr3); System.out.println("arr1 and arr3 equal: " + retval2); } } fill: You can use the fill method to fill in the whole array or part of the array. import java.util.Arrays; public class ArrayDemo { public static void main(String[] args) { // initializing int array int arr[] = new int[] {1, 6, 3, 2, 9}; // using fill for placing 18 Arrays.fill(arr, 18); for (int value : arr) { System.out.println("Value = " + value); } } }