0% found this document useful (0 votes)
22 views25 pages

Java Unit 1

Uploaded by

22eg107a11
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
22 views25 pages

Java Unit 1

Uploaded by

22eg107a11
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 25

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.

A list of the most important features of the Java


language is given below.

1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic

Simple
 Java was designed to be easy for a professional programmer to learn and use
effectively.
 It’s simple and easy to learn if you already know the basic concepts of Object
Oriented Programming.
 Best of all, if you are an experienced C++ programmer, moving to Java will
require very little effort. Because Java inherits the C/C++ syntax and many of
the object-oriented features of C++, most programmers have little trouble
learning Java.
 Java has removed many complicated and rarely-used features, for example,
explicit pointers, operator overloading, etc.

Object Oriented
 Java is a true object-oriented programming language.
 Almost the “Everything is an Object” paradigm. All program code and data
reside within objects and classes.
 The object model in Java is simple and easy to extend.
 Java comes with an extensive set of classes, arranged in packages that can be
used in our programs through inheritance.
 Object-oriented programming (OOPs) is a methodology that simplifies
software development and maintenance by providing some rules.

The basic concepts of OOPs are:

 Object
 Class
 Inheritance
 Polymorphism
 Abstraction
 Encapsulation

Distributed
 Java is designed to create distributed applications on networks.
 Java applications can access remote objects on the Internet as easily as they
can do in the local system.
 Java enables multiple programmers at multiple remote locations to
collaborate and work together on a single project.
 Java is designed for the distributed environment of the Internet because it
handles TCP/IP protocols.

Compiled and Interpreted


 Usually, a computer language is either compiled or Interpreted. Java combines
both this approach and makes it a two-stage system.
 Compiled: Java enables the creation of cross-platform programs by compiling
them into an intermediate representation called Java Bytecode.
 Interpreted: Bytecode is then interpreted, which generates machine code that
can be directly executed by the machine that provides a Java Virtual machine.

Robust
 It provides many features that make the program execute reliably in a variety
of environments.
 Java is a strictly typed language. It checks code both at compile time and
runtime.
 Java takes care of all memory management problems with garbage collection.
 Java, with the help of exception handling, captures all types of serious errors
and eliminates any risk of crashing the system.

Secure
 Java provides a “firewall” between a networked application and your
computer.
 When a Java Compatible Web browser is used, downloading can be done
safely without fear of viral infection or malicious intent.
 Java achieves this protection by confining a Java program to the Java
execution environment and not allowing it to access other parts of the
computer.

7. Architecture Neutral
 Java language and Java Virtual Machine helped in achieving the goal of “write
once; run anywhere, any time, forever.”
 Changes and upgrades in operating systems, processors and system resources
will not force any changes in Java Programs.

Portable
 Java Provides a way to download programs dynamically to all the various
types of platforms connected to the Internet.
 Java is portable because of the Java Virtual Machine (JVM). The JVM is an
abstract computing machine that provides a runtime environment for Java
programs to execute. The JVM provides a consistent environment for Java
programs to run on, regardless of the underlying hardware and operating
system. This means that a Java program can be written on one device and run
on any other device with a JVM installed, without any changes or
modifications.

9. High Performance
 Java performance is high because of the use of bytecode.
 The bytecode was used so that it can be easily translated into native machine
code
Multithreaded
 Multithreaded Programs handled multiple tasks simultaneously, which was
helpful in creating interactive, networked programs.
 Java run-time system comes with tools that support multiprocess
synchronization used to construct smoothly interactive systems.

Dynamic
 Java is capable of linking in new class libraries, methods, and objects.
 Java programs carry with them substantial amounts of run-time type
information that is used to verify and resolve accesses to objects at runtime.
This makes it possible to dynamically link code in a safe and expedient
manner.

Java Garbage Collection


In java, garbage means unreferenced objects.

Garbage Collection is process of reclaiming the runtime unused memory


automatically. In other words, it is a way to destroy the unused objects.

To do so, we were using free() function in C language and delete() in C++. But, in
java it is performed automatically. So, java provides better memory management.

o It makes java memory efficient because garbage collector removes the


unreferenced objects from heap memory.
o It is automatically done by the garbage collector(a part of JVM) so we don't
need to make extra efforts.

How can an object be unreferenced?


There are many ways:

o By nulling the reference


o By assigning a reference to another
o By anonymous object etc
1) By nulling a reference:
Employee e=new Employee();
e=null;
2) By assigning a reference to another:
Employee e1=new Employee();
Employee e2=new Employee();
e1=e2;//now the first object referred by e1 is available for garbage collection
3) By anonymous object:
new Employee();

finalize() method
The finalize() method is invoked each time before the object is garbage collected.
This method can be used to perform cleanup processing. This method is defined in
Object class as:

protected void finalize(){}

Simple Example of garbage collection in


java
public class TestGarbage1{
public void finalize(){System.out.println("object is garbage collected");}
public static void main(String args[]){
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
System.gc();
}
}
The scope of a variable refers to the areas or the sections of the program in which the variable can be
accessed, and the lifetime of a variable indicates how long the variable stays alive in the memory.

Types of Variables and its Scope


There are three types of variables.

1. Instance Variables
2. Class Variables
3. Local Variables

Local Variables:
Local variables are those that are declared inside of a method, constructor, or code
block. Only the precise block in which they are defined is accessible. The local
variable exits the block's scope after it has been used, and its memory is freed.
Temporary data is stored in local variables, which are frequently initialised in the
block where they are declared. The Java compiler throws an error if a local variable is
not initialised before being used. The range of local variables is the smallest of all the
different variable types.

Example:

public SumExample
{
public void calculateSum() {
int a = 5; // local variable
int b = 10; // local variable
int sum = a + b;
System.out.println("The sum is: " + sum);
} // a, b, and sum go out of scope here
}

Output:

The sum is: 15


Instance Variables:
Within a class, but outside of any methods, constructors, or blocks, instance variables
are declared. They are accessible to all methods and blocks in the class and are a part
of an instance of the class. If an instance variable is not explicitly initialised, its default
values are false for boolean types, null for object references, and 0 for numeric kinds.
Until the class instance is destroyed, these variables' values are retained.

Example:

public class Circle {


double radius; // instance variable
public double calculateArea() {
return Math.PI * radius * radius;
}
}

Class Variables (Static Variables):


In a class but outside of any method, constructor, or block, the static keyword is used
to declare class variables, also referred to as static variables. They relate to the class
as a whole, not to any particular instance of the class. Class variables can be accessed
by using the class name and are shared by all instances of the class. Like instance
variables, they have default values, and they keep those values until the programme
ends.

Example:

public class Bank {


static double interestRate; // class variable
// ...
}

Method Parameters:
Variables that are supplied to a method when it is invoked are known as method
parameters. They serve as inputs for method execution and are used to receive
values from the caller. The scope of method parameters is restricted to the method
in which they are defined, making them local to that method. The values of the
arguments given are allocated to the respective parameters when a method is called.

Example:
public void printName(String name) { // name is a method parameter
System.out.println("Hello, " + name + "!");
}

Writing clear and effective Java code requires a solid understanding of variable
scope. Here are some essential ideas to bear in mind:

The minimal scope necessary for variables to serve their purpose should be
expressed. As a result, there are fewer naming conflicts, and the code is easier to
comprehend.

To prevent compilation issues, local variables should be initialised before usage.

To guarantee consistent behaviour, instance and class variables should be correctly


initialised.

To encourage modular and reusable code, method parameters should be used to


send data to a method and receive return values.

In conclusion, the accessibility and longevity of variables in a Java programme


depend on the variables' scope. Developers can produce more productive, readable,
and maintainable code by comprehending and using variable scope efficiently. The
follo

public class FindGCDExample2


{
public static void main(String[] args)
{
int n1=50, n2=60;
while(n1!=n2)
{
if(n1>n2)
n1=n1-n2;
else
n2=n2-n1;
}
System.out.printf("GCD of n1 and n2 is: " +n2);
}
}
Output:

GCD of n1 and n2 is: 10

Data Types in Java


Data types specify the different sizes and values that can be stored in the variable.
There are two types of data types in Java:

1. Primitive data types: The primitive data types include boolean, char, byte, short, int,
long, float and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces,
and Arrays.

There are 8 types of primitive data types:

o boolean data type


o byte data type
o char data type
o short data type
o int data type
o long data type
o float data type
o double data type

Boolean Data Type


The Boolean data type is used to store only two possible values: true and false. This
data type is used for simple flags that track true/false conditions.

The Boolean data type specifies one bit of information, but its "size" can't be defined
precisely.

Example:

Boolean one = false


Byte Data Type
The byte data type is an example of primitive data type. It isan 8-bit signed two's
complement integer. Its value-range lies between -128 to 127 (inclusive). Its
minimum value is -128 and maximum value is 127. Its default value is 0.

The byte data type is used to save memory in large arrays where the memory savings
is most required. It saves space because a byte is 4 times smaller than an integer. It
can also be used in place of "int" data type.

byte a = 10, byte b = -20

Short Data Type


The short data type is a 16-bit signed two's complement integer. Its value-range lies
between -32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum
value is 32,767. Its default value is 0.

The short data type can also be used to save memory just like byte data type. A short
data type is 2 times smaller than an integer.

Example:

1. short s = 10000, short r = -5000

Int Data Type


The int data type is a 32-bit signed two's complement integer. Its value-range lies
between - 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum
value is - 2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.

The int data type is generally used as a default data type for integral values unless if
there is no problem about memory.

Example:

1. int a = 100000, int b = -200000

Long Data Type


The long data type is a 64-bit two's complement integer. Its value-range lies between
-9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive).
Its minimum value is - 9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807. Its default value is 0. The long data type is used when you
need a range of values more than those provided by int.
Example:

1. long a = 100000L, long b = -200000L

Float Data Type


The float data type is a single-precision 32-bit IEEE 754 floating point.Its value range
is unlimited. It is recommended to use a float (instead of double) if you need to save
memory in large arrays of floating point numbers. The float data type should never
be used for precise values, such as currency. Its default value is 0.0F.

Example:

1. float f1 = 234.5f

Double Data Type


The double data type is a double-precision 64-bit IEEE 754 floating point. Its value
range is unlimited. The double data type is generally used for decimal values just like
float. The double data type also should never be used for precise values, such as
currency. Its default value is 0.0d.

Example:

1. double d1 = 12.3

Char Data Type


The char data type is a single 16-bit Unicode character. Its value-range lies between
'\u0000' (or 0) to '\uffff' (or 65,535 inclusive).The char data type is used to store
characters.
String methods

Method Description

charAt() Returns the character at the specified index (position)

codePointAt() Returns the Unicode of the character at the specified index

codePointBefore() Returns the Unicode of the character before the specified ind

codePointCount() Returns the number of Unicode values found in a string.

compareTo() Compares two strings lexicographically

compareToIgnoreCase() Compares two strings lexicographically, ignoring case differen

concat() Appends a string to the end of another string

contains() Checks whether a string contains a sequence of characters

contentEquals() Checks whether a string contains the exact same sequence o


specified CharSequence or StringBuffer

copyValueOf() Returns a String that represents the characters of the charac

endsWith() Checks whether a string ends with the specified character(s)

equals() Compares two strings. Returns true if the strings are equal, a

equalsIgnoreCase() Compares two strings, ignoring case considerations

format() Returns a formatted string using the specified locale, format


arguments

getBytes() Encodes this String into a sequence of bytes using the named
the result into a new byte array

getChars() Copies characters from a string to an array of chars

hashCode() Returns the hash code of a string

indexOf() Returns the position of the first found occurrence of specified


string

intern() Returns the canonical representation for the string object

isEmpty() Checks whether a string is empty or not


lastIndexOf() Returns the position of the last found occurrence of specified
string

length() Returns the length of a specified string

matches() Searches a string for a match against a regular expression, a


matches

offsetByCodePoints() Returns the index within this String that is offset from the giv
codePointOffset code points

regionMatches() Tests if two string regions are equal

replace() Searches a string for a specified value, and returns a new str
specified values are replaced

replaceFirst() Replaces the first occurrence of a substring that matches the


expression with the given replacement

replaceAll() Replaces each substring of this string that matches the given
with the given replacement

split() Splits a string into an array of substrings

startsWith() Checks whether a string starts with specified characters

subSequence() Returns a new character sequence that is a subsequence of t

substring() Returns a new string which is the substring of a specified stri

toCharArray() Converts this string to a new character array

toLowerCase() Converts a string to lower case letters

toString() Returns the value of a String object

toUpperCase() Converts a string to upper case letters

trim() Removes whitespace from both ends of a string

valueOf() Returns the string representation of the specified value


Constructors in Java

n Java, a constructor is a block of codes similar to the method. It is called when an


instance of the class is created. At the time of calling constructor, memory for the
object is allocated in the memory.

It is a special type of method which is used to initialize the object.

Every time an object is created using the new() keyword, at least one constructor is
called.

It calls a default constructor if there is no constructor available in the class. In such


case, Java compiler provides a default constructor by default.

Types of Java constructors


There are two types of constructors in Java:

1. Default constructor (no-arg constructor)


2. Parameterized constructor

Java Default Constructor


A constructor is called "Default Constructor" when it doesn't have any parameter.

Syntax of default constructor:


1. <class_name>(){}
Example of default constructor
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of obje

//Java Program to create and call a default constructor


class Bike1{
//creating a default constructor
Bike1(){System.out.println("Bike is created");}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}

Java Parameterized Constructor


A constructor which has a specific number of parameters is called a parameterized
constructor.

Why use the parameterized constructor?

The parameterized constructor is used to provide different values to distinct objects.


However, you can provide the same values also.

Example of parameterized constructor


In this example, we have created the constructor of Student class that have two
parameters. We can have any number of parameters in the constructor.

//Java Program to demonstrate the use of the parameterized constructor.


class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display();
}
}

Difference between method


overloading and method overriding in
java
There are many differences between method overloading and method overriding in
java. A list of differences between method overloading and method overriding are
given below:

No Method Overloading Method Overriding


.

1) Method overloading is used to increase the readability of the Method overriding is used
program. implementation of the me
provided by its super class

2) Method overloading is performed within class. Method overriding occur


have IS-A (inheritance) rela

3) In case of method overloading, parameter must be different. In case of method overri


be same.

4) Method overloading is the example of compile time polymorphism. Method overriding is the
polymorphism.

5) In java, method overloading can't be performed by changing return Return type must be s
type of the method only. Return type can be same or different in method overriding.
method overloading. But you must have to change the parameter.

Java Method Overloading example


class OverloadingExample{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}

Java Method Overriding example


class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
import java.lang.*;
string reverse

import java.io.*;
import java.util.*;

// Class of ReverseString
class ReverseString {
public static void main(String[] args)
{
String input = "Geeks for Geeks";

StringBuilder input1 = new StringBuilder();

// append a string into StringBuilder input1


input1.append(input);

// reverse StringBuilder input1


input1.reverse();

// print reversed String


System.out.println(input1);
}
}

Palindrome
class PalindromeExample{
public static void main(String args[]){
int r,sum=0,temp;
int n=454;//It is the number variable to be checked for palindrome
temp=n;
while(n>0){
r=n%10; //getting remainder
sum=(sum*10)+r;
n=n/10;
}
if(temp==sum)
System.out.println("palindrome number ");
else
System.out.println("not palindrome");
}

Structure of Java Program


object-oriented programming, platform-independent, and secure programming
language that makes it popular. Using the Java programming language, we can
develop a wide variety of applications. So, before diving in depth, it is necessary to
understand the basic structure of Java program in detail. In this section, we have
discussed the basic structure of a Java program. At the end of this section, you will
able to develop the Hello world Java program, easily.

Let's see which elements are included in the structure of a Java program. A typical
structure of a Java program contains the following elements:
There are two types of Java programs — Java Stand-Alone Applications and Java Applets.

Java Stand-Alone Applications


A stand-alone Java application refers to a Java program that can run independently on a
computer. Acrobat Reader is an excellent example of this type of application. In Java, every
stand-alone application begins its execution with the main() method. Java stand-alone
applications can be classified into two types:
a. Console based applications
b. Graphical User Interface based applications

Java Applets
Java applets are Java applications that run within a web browser. They are mainly used for
internet programming. The applet is capable of performing many tasks on a web page, such
as displaying graphics, playing sounds, and accepting user input

List the Java Tokens and discuss in detail

Java Tokens
In Java, the program contains classes and methods. Further, the methods contain the
expressions and statements required to perform a specific operation. These
statements and expressions are made up of tokens. In other words, we can say that
the expression and statement is a set of tokens. The tokens are the small building
blocks of a Java program that are meaningful to the Java compiler. Further, these two
components contain variables, constants, and operators. In this section, we will
discuss what is tokens in Java.

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.

1. token <= identifier | keyword | separator | operator | literal | comment

Types of Tokens
Java token includes the following:

o Keywords
o Identifiers
o Literals
o Operators
o Separators
o Comments

Keywords: These are the pre-defined reserved words of any programming


language. Each keyword has a special meaning. It is always written in lower case. Java
provides the following keywords:

w
01. abstract 02. boolean 03. byte 04. break 05. class

06. case 07. catch 08. char 09. continue 10. default

11. do 12. double 13. else 14. extends 15. final

16. finally 17. float 18. for 19. if 20. implements

21. import 22. instanceof 23. int 24. interface 25. long

26. native 27. new 28. package 29. private 30. protected

31. public 32. return 33. short 34. static 35. super

36. switch 37. synchronized 38. this 39. thro 40. throws

41. transient 42. try 43. void 44. volatile 45. while

46. assert 47. const 48. enum 49. goto 50. strictfp

Identifier: Identifiers are used to name a variable, constant, function, class, and array.
It usually defined by the user. It uses letters, underscores, or a dollar sign as the first
character. The label is also known as a special kind of identifier that is used in the
goto statement. Remember that the identifier name must be different from the
reserved keywords. There are some rules to declare identifiers are:

o The first letter of an identifier must be a letter, underscore or a dollar sign. It


cannot start with digits but may contain digits.
o The whitespace cannot be included in the identifier.
o Identifiers are case sensitive.

Literals: In programming literal is a notation that represents a fixed value (constant) in the
source code. It can be categorized as an integer literal, string literal, Boolean literal, etc. It is
defined by the programmer. Once it has been defined cannot be changed. Java provides five
types of literals are as follows:

o Integer
o Floating Point
o Character
o String
o Boolean

Operators: In programming, operators are the special symbol that tells the compiler
to perform a special operation. Java provides different types of operators that can be
classified according to the functionality they provide. There are eight types
of operators in Java, are as follows:

o Arithmetic Operators
o Assignment Operators
o Relational Operators
o Unary Operators
o Logical Operators
o Ternary Operators
o Bitwise Operators

Arithmetic multiplicative * / %

additive + -

Shift shift << >> >>>

Relational comparison < > <= >= instanceof

equality == !=

Bitwise bitwise AND &

bitwise exclusive OR ^
bitwise inclusive OR |

Logical logical AND &&

logical OR ||

Ternary ternary ? :

Assignment assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

Java operators are symbols that are used to perform operations on variables and manipulate the values
of the operands. Each operator performs specific operations. Let us consider an expression 5 + 1 = 6;
here, 5 and 1 are operands, and the symbol + (plus) is called the operator. We will also learn about
operator precedence and operator associativity.

java Arithmetic Operator Example


public class OperatorExample{
public static void main(String args[]){
int a=10;
int 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%b);//0
}}

Java Left Shift Operator


The Java left shift operator << is used to shift all of the bits in a value to the left side
of a specified number of times.

Java Left Shift Operator Example


public class OperatorExample{
public static void main(String args[]){
System.out.println(10<<2);//10*2^2=10*4=40
System.out.println(10<<3);//10*2^3=10*8=80
System.out.println(20<<2);//20*2^2=20*4=80
System.out.println(15<<4);//15*2^4=15*16=240
}}

Java AND Operator Example: Logical && and


Bitwise &
The logical && operator doesn't check the second condition if the first condition is
false. It checks the second condition only if the first one is true.

The bitwise & operator always checks both conditions whether first condition is true
or false.

public class OperatorExample{


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

Output:

false
false

Java Ternary Operator Example


public class OperatorExample{
public static void main(String args[]){
int a=2;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}}
Output:

Java Assignment Operator


Java assignment operator is one of the most common operators. It is used to assign
the value on its right to the operand on its left.

Java Assignment Operator Example


public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=20;
a+=4;//a=a+4 (a=10+4)
b-=4;//b=b-4 (b=20-4)
System.out.println(a);
System.out.println(b);
}}

You might also like