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

Java 1st ch

Java is a high-level, robust, object-oriented programming language developed by Sun Microsystems in 1995. It features platform independence, security, and automatic garbage collection, making it popular for software development. Key concepts include object-oriented programming principles such as inheritance, polymorphism, abstraction, and encapsulation.

Uploaded by

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

Java 1st ch

Java is a high-level, robust, object-oriented programming language developed by Sun Microsystems in 1995. It features platform independence, security, and automatic garbage collection, making it popular for software development. Key concepts include object-oriented programming principles such as inheritance, polymorphism, abstraction, and encapsulation.

Uploaded by

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

Java

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

• Any entity that has state and behavior is known as an


object. For example, a chair, pen, table, keyboard, bike,
etc. It can be physical or logical.

• An Object can be defined as an instance of a class. An


object contains an address and takes up some space in
memory. Objects can communicate without knowing the
details of each other's data or code. The only necessary
thing is the type of message accepted and the type of
response returned by the objects.

• Example: A dog is an object because it has states like


color, name, breed, etc. as well as behaviors like wagging
the tail, barking, eating, etc.
class

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


entity.
• A class can also be defined as a blueprint from which
you can create an individual object. Class doesn't
consume any space.

Inheritance

• When one object acquires all the properties and behaviors of a


parent object, it is known as inheritance. It provides code
reusability. It is used to achieve runtime polymorphism.
Polymorphism

• If one task is performed in different ways, it is known


as polymorphism. For example: to convince the
customer differently, to draw something, for example,
shape, triangle, rectangle, etc.

• In Java, we use method overloading and method


overriding to achieve polymorphism.

• Another example can be to speak something; for


example, a cat speaks meow, 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 are known as encapsulation. For example,
a 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.
Features of java

• The primary objective of Java programming


language creation was to make it portable,
simple and secure programming language.
Apart from this, there are also some excellent
features which play an important role in the
popularity of this language. The features of
Java are also known as Java buzzwords.
 Simple
• Java is very easy to learn, and its syntax is simple, clean and easy to understand.
According to Sun Microsystem, Java language is a simple programming language
because:

• 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.

• Object-oriented means we organize our software as a


combination of different types of objects that
incorporate both data and behavior.
Platform Independent
• Java is platform independent
• Java is platform independent because it is different from
other languages like C,C++, etc.
• which are compiled into platform specific machines while
Java is a write once, run anywhere language. A platform is
the hardware or software environment in which a
program runs.
• There are two types of platforms software-based and
hardware-based. Java provides a software-based
platform.

 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

• We can create document api in java by the help of javadoc tool. In


the java file, we must use the documentation comment /**... */ to
post information for the class, method, constructor, fields etc.

• Let's see the simple class that contains documentation comment.

• package com.abc;
/** This class is a user-defined class that contains one methods
cube.*/
public class M{

/** The cube method prints cube of the given number */


public static void cube(int n){System.out.println(n*n*n);}
}
Jar
• JAR is short for Java Archive. JAR files contain compressed Java project files. It includes the .class files and
other metadata and resources needed for the project.

• 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.

Creating JAR Files


A JAR file is composed of the compiled Java .class files and other resources. We can create an executable or
a non-executable JAR.

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:

• Primitive data types: The primitive data types include


boolean, char, byte, short, int, long, float and double.

• Non-primitive data types: The non-primitive data


types include Classes, Interfaces, and Arrays.
Tokens

What is token in Java?


• The Java compiler breaks the line of code into text (words) is called
Java tokens. These are the smallest element of the Java program.
The Java compiler identified these words as tokens. These tokens
are separated by the delimiters. It is useful for compilers to detect
errors. Remember that the delimiters are not part of the Java
tokens.

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.

Example of final method Example of final class


class Bike{ final class Bike{}
final void run(){System.out.println("running");}
} class Honda1 extends Bike{
void run(){System.out.println("running
class Honda extends Bike{ safely with 100kmph");}
void run(){System.out.println("running safely
with 100kmph");} public static void main(String args[]){
Honda1 honda= new Honda1();
public static void main(String args[]){ honda.run();
Honda honda= new Honda(); }
honda.run(); }
}
}
Control Statement
• Control statements decide the flow (order or sequence of execution of statements) of a
Java program. In Java, statements are parsed from top to bottom. Therefore, using the
control flow statements can interrupt a particular section of a program based on a
certain condition.
Conditional statement

• 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 {

public static void main(String[] args) {


Unlike break statement, the continue // TODO Auto-generated method stub
statement doesn't break the loop, whereas, it
skips the specific part of the loop and jumps to for(int i = 1; i<= 10; i++) {
the next iteration of the loop immediately. if(i==5){
continue;
}
System.out.pritln(i);
}
}
}

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.

Q.How to get input from user in Java


float nextFloat() It is used to scan the next token of the input as a float.
Java Scanner Class ?
=>
Java Scanner class allows the user to take double nextDouble() It is used to scan the next token of the input as a double.

input from the console. It belongs


to java.util package. It is used to read the byte nextByte() It is used to scan the next token of the input as a byte.
input of primitive types like int, double,
long, short, float, and byte. It is the easiest
String nextLine() Advances this scanner past the current line.
way to read input in Java program.

Syntax: boolean nextBoolean() It is used to scan the next token of the input into a boolean value.

1.Scanner sc=new Scanner(System.in);


long nextLong() It is used to scan the next token of the input as a long.

It also converts the Bytes (from the input


stream) into characters using the platform's short nextShort() It is used to scan the next token of the input as a Short.
default charset.
BigInteger nextBigInteger() It is used to scan the next token of the input as a BigInteger.
Methods of Java Scanner Class
Java Scanner class provides the following
methods to read different primitives types: BigDecimal nextBigDecimal() It is used to scan the next token of the input as a BigDecimal.
Example of integer input from user

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:

How to get input from user in Java


Example of String Input from user

Let's see another example, in which we have taken string input.

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:

How to get input from user in Java


Java BufferedReader Class //Example

Java BufferedReader class is used to read the text package com.javatpoint;


from a character-based input stream. It can be import java.io.*;
used to read data line by line by readLine() public class BufferedReaderExample {
method. It makes the performance fast. It inherits public static void main(String args[])throws Exception{
Reader class. FileReader fr=new FileReader("D:\\testout.txt");
BufferedReader br=new BufferedReader(fr);

Java BufferedReader class declaration int i;


Let's see the declaration for while((i=br.read())!=-1){
Java.io.BufferedReader class: System.out.print((char)i);
}
public class BufferedReader extends Reader br.close();
fr.close();
}
}

You might also like