Java 1st ch
Java 1st ch
By Komal Konkati
What is Java ? & It’s History
What is Java?
Java is a programming language and a platform. Java is a high level, robust, object-oriented
and secure programming language.
Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the year
1995. James Gosling is known as the father of Java. Before Java, its name was Oak. Since Oak
was already a registered company, so James Gosling and his team changed the name from
Oak to Java.
Platform: Any hardware or software environment in which a program runs, is known as a
platform. Since Java has a runtime environment (JRE) and API, it is called a platform.
Simple.java
class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
}
}
Object Oriented programming
Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-
Oriented Programming is a methodology or paradigm to design a program using classes and
objects. It simplifies software development and maintenance by providing some concepts:
Object
Inheritance
Encapsulation
• Java syntax is based on C++ (so easier for programmers to learn it after C++).
Java has removed many complicated and rarely-used features, for example,
explicit pointers, operator overloading, etc.
There is no need to remove unreferenced objects because there is an
Automatic Garbage Collection in Java.
Object-oriented
• Java is an object-oriented
programming language. Everything in Java is an object.
Secured
• Java is best known for its security. With Java, we can
develop virus-free systems. Java is secured because:
• No explicit pointer
• Java Programs run inside a virtual machine sandbox
Robust
• The English mining of Robust is strong. Java is robust because:
• It uses strong memory management.
There is a lack of pointers that avoids security problems.
• Java provides automatic garbage collection which runs on the Java Virtual Machine to get rid of objects
which are not being used by a Java application anymore.
• There are exception handling and the type checking mechanism in Java. All these points make Java robust.
Architecture-neutral
• Java is architecture neutral because there are no implementation dependent features, for example, the
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. However, it occupies 4 bytes of memory for both 32 and 64-bit
architectures in Java.
Portable
• Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't require
any implementation.
High-performance
• Java is faster than other traditional interpreted programming languages because Java bytecode is
"close" to native code. It is still a little bit slower than a compiled language (e.g., C++). Java is an
interpreted language that is why it is slower than compiled languages, e.g., C, C++, etc.
Distributed
• Java is distributed because it facilitates users to create distributed applications in Java. RMI and EJB
are used for creating distributed applications. This feature of Java makes us able to access files by
calling the methods from any machine on the internet.
Multi-threaded
• A thread is like a separate program, executing concurrently. 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, etc.
Dynamic
• Java is a dynamic language. It supports the dynamic loading of classes. It means classes are loaded
on demand. It also supports functions from its native languages, i.e., C and C++.
JavaDoc Tool
• package com.abc;
/** This class is a user-defined class that contains one methods
cube.*/
public class M{
• JAR files are a great way to share and distribute our Java code with others.
• In this short tutorial, we will learn how to create and run a JAR file in Java.
The difference between the two is that an executable JAR file contains a manifest file, while the non-
executable JAR file does not contain this. This manifest file contains the name of the class that should be
executed when the JAR is run.
Data Types
Data types specify the different sizes and values that can
be stored in the variable. There are two types of data
types in Java:
Types of Tokens
Java token includes the following:
• Keywords
• Identifiers
• Literals
• Operators
• Separators
• Comments
Java Variables
• A variable is the name of a reserved area allocated in memory. In other words, it is a name of the
memory location. It is a combination of "vary + able" which means its value can be changed.
Types of Variables
There are three types of variables in Java 2) Instance Variable
• local variable • A variable declared inside the class but outside the body of
the method, is called an instance variable. It is not declared
• instance variable
as static.
• static variable
• It is called an instance variable because its value is instance-
1) Local Variable specific and is not shared among instances.
• A variable declared inside the body of the method
is called local variable. You can use this variable
only within that method and the other methods in 3) Static variable
the class aren't even aware that the variable exists. • A variable that is declared as static is called a static variable.
It cannot be local. You can create a single copy of the static
• A local variable cannot be defined with "static" variable and share it among all the instances of the class.
keyword. Memory allocation for static variables happens only once
when the class is loaded in the memory.
Final Keyword In Java
• Final variable
• Final method
• Final class
The final keyword can be applied with the
variables, a final variable that have no value it Example:
is called blank final variable or uninitialized
final variable. It can be initialized in the class Bike9{
constructor only. The blank final variable can final int speedlimit=90;//final variable
be static also which will be initialized in the void run(){
static block only. We will have detailed speedlimit=400;
learning of these. Let's first learn the basics of }
final keyword. public static void main(String args[]){
Bike9 obj=new Bike9();
final keyword in java
obj.run();
1) Java final variable }
If you make any variable as final, you cannot }
change the value of final variable(It will be
constant).
2)Java final method 3)Java final class
If you make any method as final, you cannot If you make any class as final, you cannot
override it. extend it.
• if statement
• if-else statement
• if-else-if ladder
• nested if statement
Java if-else Statement
• Java If statement
• Java Program to demonstate the use of if A Java Program to demonstrate the use of if-else statement.
statement. • It is a program of odd and even number.
public class IfElseExample {
public class IfExample {
public static void main(String[] args) {
public static void main(String[] args) {
//defining a variable
//defining an 'age' variable int number=13;
int age=20; //Check if the number is divisible by 2 or not
//checking the age if(number%2==0){
if(age>18){ System.out.println("even number");
System.out.print("Age is greater than 18"); }else{
} System.out.println("odd number");
} }
}
}
}
Java if-else-if ladder Statement Java Nested if else
J//ava Program to demonstrate the use of If //Java Program to demonstrate the use of Nested If
else-if ladder. Statement.
public class PositiveNegativeExample { public class JavaNestedIfExample {
public static void main(String[] args) { public static void main(String[] args) {
int number=-13; //Creating two variables for age and weight
if(number>0){ int age=20;
System.out.println("POSITIVE"); int weight=80;
}else if(number<0){ //applying condition on age and weight
System.out.println("NEGATIVE"); if(age>=18){
}else{ if(weight>50){
System.out.println("ZERO"); System.out.println("You are eligible to donate
} blood");
} }
} }
}}
Switch Statement:
In Java, Switch statements are similar to if-else-if public class Student {
statements. The switch statement contains multiple public static void main(String[] args) {
int num = 2;
blocks of code called cases and a single case is executed
switch (num){
based on the variable which is being switched. The case 0:
switch statement is easier to use instead of if-else-if System.out.println("number is 0");
statements. It also enhances the readability of the break;
program. case 1:
System.out.println("number is 1");
break;
default:
System.out.println(num);
}
}
}
Loop Statements Java for-each loop
Java provides an enhanced for loop to traverse the data
1.for loop structures like array or collection. In the for-each loop, we don't
2.while loop need to update the loop variable.
3.do-while loop
Calculation.java
Java for loop
public class Calculation {
Calculation.java public static void main(String[] args) {
String[] names = {"Java","C","C++","Python","JavaScript"};
public class Calculattion { System.out.println("Printing the content of the array
public static void main(String[] args) { names:\n");
// TODO Auto-generated method stub for(String name:names) {
int sum = 0; System.out.println(name);
for(int j = 1; j<=10; j++) { }
sum = sum + j; }
} }
System.out.println("The sum of first 10 natural Output:
numbers is " + sum);
} Printing the content of the array names:
}
Output: Java Python
JavaScript
The sum of first 10 natural numbers is 55 C++
Java while loop Java do-while loop
//Calculation .java //Calculation.java
public class Calculation {
public static void main(String[] args) { public class Calculation {
public static void main(String[] args) {
int i = 0; int i = 0;
System.out.println("Printing the list of first 10 System.out.println("Printing the list of first 10 even number
even numbers \n"); \n");
while(i<=10) { do {
System.out.println(i); System.out.println(i);
i = i + 2; i = i + 2;
} }while(i<=10);
} }
} }
Output: Output:
Printing the list of first 10 even numbers Printing the list of first 10 even numbers
0
0 2
2 4
4 6
6 8
8 10
10
Jump Statements
BreakExample.java
Java break statement
As the name suggests, the break public class BreakExample {
statement is used to break the current
flow of the program and transfer the public static void main(String[] args) {
control to the next statement outside
a loop or switch statement. However for(int i = 0; i<= 10; i++) {
System.out.println(i);
if(i==6) {
break;
}
}
}
}
Output:
0
1
2
3
4
5
6
Java continue statement public class ContinueExample {
Output:
0 1 2 3 4 6 7 8 9 10
Java Arrays
Java array is an object which contains elements of a
similar data type. Additionally, The elements of an array
are stored in a contiguous memory location. It is a data
structure where we store similar elements. We can store
only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array
is stored at the 0th index, 2nd element is stored on 1st
index and so on.
Advantages
•Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
•Random access: We can get any data located at an index position.
Disadvantages
•Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at
runtime. To solve this problem, collection framework is used in Java which grows automatically.
Types of Array in java class Testarray
There are two types of array. {
public static void main(String args[]){
• Single Dimensional Array int a[]=new int[5];//declaration and instantiation
• Multidimensional Array a[0]=10;//initialization
a[1]=20;
Single Dimensional Array in Java a[2]=70;
Syntax to Declare an Array in Java a[3]=40;
a[4]=50;
dataType[] arr; (or) //traversing array
dataType []arr; (or) for(int i=0;i<a.length;i++)//length is the property of array
dataType arr[]; System.out.println(a[i]);
}
Instantiation of an Array in Java }
Test it Now
arrayRefVar=new datatype[size]; Output:
10
20
70
40
50
2D Array
Example
A multidimensional array is an array of public class Main {
arrays. public static void main(String[] args) {
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
To create a two-dimensional array, add each for (int i = 0; i < myNumbers.length; ++i) {
array within its own set of curly braces: for(int j = 0; j < myNumbers[i].length; ++j) {
System.out.println(myNumbers[i][j]);
Example }
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} }; }
}
}
Accepting Inputs Method Description
int nextInt() It is used to scan the next token of the input as an integer.
Syntax: boolean nextBoolean() It is used to scan the next token of the input into a boolean value.
The following example allows user to read an integer form the System.in.
import java.util.*;
class UserInputDemo
{
public static void main(String[] args)
{
Scanner sc= new Scanner(System.in); //System.in is a standard input stream
System.out.print("Enter first number- ");
int a= sc.nextInt();
System.out.print("Enter second number- ");
int b= sc.nextInt();
System.out.print("Enter third number- ");
int c= sc.nextInt();
int d=a+b+c;
System.out.println("Total= " +d);
}
}
Output:
import java.util.*;
class UserInputDemo1
{
public static void main(String[] args)
{
Scanner sc= new Scanner(System.in); //System.in is a standard input stream
System.out.print("Enter a string: ");
String str= sc.nextLine(); //reads string
System.out.print("You have entered: "+str);
}
}
Output: