SlideShare a Scribd company logo
Unit - III
ARRAYS ,STRINGS AND VECTORS
Introduction to arrays:
•Array- group of a related data items that are common name.
•Index-to indicate the particular value.
Example: salary[100]
•Individual values are called the elements.
The values are assigned as follows:
Number [0]=40;
Number[1] = 55;
Number [2]=63;
Number [3]=17;
Number [4]=22;
Number [5]=68;
Number [6]=89;
Number [7]=97;
Number [8]=89;
Creating an array:
Array should be declared and created before they are used. Creation of array consist of three
steps: 1. Declaring the array
2. Creating memory locations
3.putting values into memory locations.
Declaring the array:
The general form of a one-dimensional array declaration is
Example ;
type var-name[];
type[] var-name;
Creation of arrays:
New operator is used
Syntax:
Array name= new type[size];
Number = new int [5];
Initialization of arrays:
Initialisation put values into created array.
Two ways:
1.syntax:
Array name[subscript] = value;
2.syntax:
Type array name [] = { list of values};
•Array initialisation- list of values are separated by Sunday surrounded by curly braces.
Example:
Int num[]= {10,20,30,40,50}
Example:
Import java.io.*;
class arraysize {
public static void main (String[] args) {
int [] arr=new int [4];
System.out.println(“Array Size:”+arr.length);
}
}
Output
Array Size:4
Two dimensional array:
It have different rows and columns
Syntax:
datatype [][] arrayrofvariable;
datatype arrayrofvariable[][];
Example:
Public class multiDimensional {
public static void main(String args[])
{
int arr[][]
= { { 2, 7, 9 }, { 3, 6, 1 }, { 7, 4, 2 }
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++)
System.out.print(arr[i][j] + “ “);
System.out.println();
}
}
}
Output
2 7 9
3 6 1
7 4 2
STRING:
 Sequence of characters.
 Character array-easiest way to represent the strings.
Strings are the type of objects that can store the character of values and in
Java, every character is stored in 16 bits.
Example:
String name = “Geeks”;
Ways of creating a string:
There are two ways to create a string in Java:
•String Literal
•Using new Keyword.
Syntax:
<String_Type>
<string_variable> = “<sequence_of_string>”;
1. String literal
To make Java more memory efficient (because no new objects are created if it exists already in the string
constant pool).
Example:
String demoString = “helloworld”;
2. Using new keyword
String s = new String(“Welcome”);
In such a case, JVM will create a new string object in normal (non-pool) heap memory and the literal
“Welcome” will be placed in the string constant pool. The variable s will refer to the object in the heap (non-
pool)
Example:
String demoString = new String (“helloworld”);
String arrays:
Users can Also create and use arrays that contains string
String itemarray [] = new string [];
String methods:
S2= S1.to lowercase;  converts the string s1 to all lowercase.
S2=S1.to uppercase;  converts the string S1 to all uppercase
S2=S1.replace(‘X’ , ‘Y’) replace all appearance to X with Y
S2=S.trim() remove white space at the beginning and end of the string S1.
S1.equals Or ignore case(S2) returns true.if S1=S2. Ignoring the case of characters.
S1.length() gives the length of S1.
CharSequence Interface
.
CharSequence Interface is used for representing the sequence of Characters in Java.
Classes that are implemented using the CharSequence interface are mentioned below and these provides
much of functionality like substring, lastoccurence, first occurence, concatenate.
1.String
2.StringBuffer
3 .StringBuilder
•String:
. String is an immutable class which means a constant and cannot be changed once
created.
Syntax:
String str= “hello”;
•String buffer:
StringBuffer is a peer class of String, it is mutable in nature and it is thread safe class .we
can use it when we have multi threaded environment and shared object of string buffer .
Syntax:
StringBuffer demoString = new StringBuffer(“hello”);
• String builder
StringBuilder in Java represents an alternative to String and StringBuffer Class, as it creates a
mutable sequence of characters and it is not thread safe.
Syntax:
StringBuilder demoString = new StringBuilder();
demoString.append(“hello”);
Example:
Import java.io.*;
class string {
public static void main(String[] args)
{
String name = “Sachin”;
name = name.concat(“ Tendulkar”);
System.out.println(name);
}
}
Output:
Sachin Tendulkar
Vectors:
The Vector class implements a growable array of objects. Vectors fall in legacy classes, but now it is
fully compatible with collections. It is found in java.util package and implement the List interface, so we can
use all the methods of the List interface.
•Vector implements a dynamic array which means it can grow or shrink as required. Like an array, it
contains components that can be accessed using an integer index.
•They are very similar to ArrayList
Syntax:
Vector variable= new vector ();
Methods Description
1). List.addElement(item)
Adds the item specified to the list at the end.
2). List.elementAt(10) Gives the name of the 10th
object
3). List.size() Gives the number of object .
4). List.copyInto(array) Copies all items from list to array.
5). List.removesAllElements() Removed all the element from the list.
Wrapper classes:
Convert primitive data types into object types.
•Primitive Data Type. • Wrapper class
char character
byte Byte
short Short
int Integer
long Long
float. Float
double Double
boolean Boolean
Autoboxing and unboxing:
•converting primitive data types to wrapper classes is called autoboxing.
•from rapper class two primitive classes is called unboxing.
•null type to any primitive type
. •convert to the null type other than the identity conversion.
• convert from any class type c to any array type.
Enumerated:
Uses enum keyword .enumeration is a class type. Although we don’t need to instantiate an
enum using new, it has the same capabilities as other classes. This fact makes Java enumeration a
very powerful tool. Just like classes, you can give them constructors, add instance variables and
methods, and even implement interfaces.
Import java.util.Scanner;
enum Day {
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY;
}
Public class Test {
Day day;
public Test(Day day) {
this.day = day;
}
public void dayIsLike() {
switch (day) {
case MONDAY:
System.out.println(“Mondays are bad.”);
break;
case FRIDAY:
System.out.println(“Fridays are better.”);
break;
Case SATURDAY:
case SUNDAY:
System.out.println(“Weekends are best.”);
break;
default:
System.out.println(“Midweek days are so-so.”);
break;
}
}
public static void main(String[] args) {
String str = “MONDAY”;
Test t1 = new Test(Day.valueOf(str));
t1.dayIsLike();
}
}
Output
Mondays are bad.
Annotations:
•Annotations are used to provide supplemental information about a program.
•Annotations start with ‘@’.
•Annotations do not change the action of a compiled program.
•Annotations help to associate metadata (information) to the program elements i.e. Instance
variables, constructors, methods, classes, etc.
•Annotations are not pure comments as they can change the way a program is treated by the
compiler.
Annotation 1: @Deprecated
It is a marker annotation. It indicates that a declaration is obsolete and has been replaced by a
newer form.
Annotation 2: @Override
It is a marker annotation that can be used only on methods. A method annotated with @Override must overrid
a method from
a superclass. If it doesn’t, a compile-time error will result (see this for example). It is used to ensure that a
superclass method is actually overridden, and not simply overloaded.
Annotation 3: @SuppressWarnings
It is used to inform the compiler to suppress specified compiler warnings. The warnings to suppress are
specified by name, in string form. This type of annotation can be applied to any type of declaration.
. Java groups warnings under two categories. They are deprecated and unchecked. Any unchecked
warning is generated when a legacy code interfaces with a code that uses generics.
Annotation 4: @Documented
It is a marker interface that tells a tool that an annotation is to be documented. Annotations are not included in
‘Javadoc’ comments. The use of @Documented annotation in the code enables tools like Javadoc to process
and include the annotation type information in the generated document.
Annotation 5: @Target
It is designed to be used only as an annotation to another annotation. @Target takes one argument, which mus
be constant
Interfaces: multiple inheritance
Java provides the concept of interfaces to support multiple inheritance. Java class cannot be
sub class of more than one class. It can be implement more than one interface.
Defining interfaces:
Interfaces is basically a kind of class.
Interfaces contain methods and variables but no coding to implement these methods and variables
Syntax:
Interface interface name {
Variable declaration;
Method declaration;
}
To declare an interface, use the interface keyword. It is used to provide total abstraction. That means all the
methods in an interface are declared with an empty body and are public and all fields are public, static,
and final by default. A class that implements an interface must implement all the methods declared in the
interface. To implement the interface, use the implements keyword.
Annotation 6: @Inherited
@Inherited is a marker annotation that can be used only on annotation declaration. It affects only
annotations that will be used on class declarations. @Inherited causes the annotation for a superclass to
be inherited by a subclass. Therefore, when a request for a specific annotation is made to the subclass, if
that annotation is not present in the subclass, then its superclass is checked. If that annotation is present
in the superclass, and if it is annotated with @Inherited, then that annotation will be returned.
Extending Interfaces
•One interface can inherit another by the use of keyword extends. When a class
implements an interface that inherits another interface, it must provide an implementation
for all methods required by the interface inheritance chain.
Example:
Interface Student {
public void data();
}
class avi implements Student {
public void data () {
String name=“avinash”;
int rollno=68;
System.out.println(name);
System.out.println(rollno);
}
}
public class inter_face {
public static void main (String args []) {
avi h= new avi();
h.data();
}
}
Output
avinash
68
Multiple Inheritance in Java Using Interface
Multiple Inheritance is an OOPs concepts that can’t be implemented in Java using classes.
But we can use multiple inheritances in Java using Interface. Let us check this with an example.
Relationship Between Class and Interface
A class can extend another class similar to this an interface can extend another interface. But only a class
can extend to another interface, and vice-versa is not allowed.
Packages:
Grouping up of variety of classes and interfaces together.
Packages acts as a container for classes.
Classes contained in the package of other programs can be used.
Types of packages:
Built-in Packages
These packages consist of a large number of classes which are a part of Java API.Some of the commonly
used built-in packages are:
•java.lang: Contains language support classes(e.g classes which defines primitive data types, math
operations). This package is automatically imported.
Java.io: Contains classes for supporting input / output operations.
Java.util: Contains utility classes which implement data structures like Linked List, Dictionary and support ;
for Date / Time operations.
Java.applet: Contains classes for creating Applets.
Java.awt: Contain classes for implementing the components for graphical user interfaces (like
button , ;menus etc). 6)
java.net: Contain classes for supporting networking operations
User-defined packages:
These are the packages that are defined by the user. First we create a directory myPackage
(name should be same as the name of the package). Then create the MyClass inside the
directory with the first statement being the package names.
Package naming conventions : Packages are named in reverse order of domain names, i.e.,
org.geeksforgeeks.practice. For example, in a college, the recommended convention is
college.tech.cse, college.tech.ee, college.art.history, etc.
Adding a class to a Package : We can add more classes to a created package by using package
name at the top of the program and saving it in the package directory. We need a new java file to
define a public class, otherwise we can add the new class to an existing .java file and recompile it.
Subpackages: Packages that are inside another package are the subpackages. These are not
imported by default, they have to imported explicitly. Also, members of a subpackage have no
access privileges, i.e., they are considered as different package for protected and default access
specifiers.
Example :
import java.util.*;
util is a subpackage created inside java package.
Accessing classes inside a package
Consider following two statements :
Import java.util.vector;
import java.util.*;
First Statement is used to import Vector class from util package which is contained inside
java.
Second statement imports all the classes from util package.
Example:
Import java.util.Vector;
public class ImportDemo
{
public ImportDemo() {
Vector newVector = new Vector();
Java.util.ArrayList newList = new java.util.ArrayList();
}
public static void main(String arg[]) {
new ImportDemo();
}
}
DOC-20240812-WA0000 array string and.pptx
DOC-20240812-WA0000 array string and.pptx
DOC-20240812-WA0000 array string and.pptx
DOC-20240812-WA0000 array string and.pptx
DOC-20240812-WA0000 array string and.pptx
DOC-20240812-WA0000 array string and.pptx
Multithreading programming:
Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for
maximum utilization of CPU. Each part of such program is called a thread. So, threads are light-weight
processes within a process.
Threads can be created by using two mechanisms :
1.Extending the Thread class
2.Implementing the Runnable Interface
Thread creation by extending the Thread class
We create a class that extends the java.lang.Thread class. This class overrides the run() method
available in the Thread class. A thread begins its life inside run() method. We create an object of our new clas
and call start() method to start the execution of a thread. Start() invokes the run() method on the Thread
object.
Example:
Class MultithreadingDemo extends Thread {
public void run() {
try {
System.out.println(
“Thread “ + Thread.currentThread().getId()
+ “ is running”);
}
catch (Exception e) {
System.out.println(“Exception is caught”);
}
}
}
public class Multithread {
public static void main(String[] args) {
int n = 8;
for (int i = 0; i < n; i++) {
MultithreadingDemo object
= new MultithreadingDemo();
object.start();
}
}
}
Output:
Thread 15 is running
Thread 14 is running
Thread 16 is running
Thread 12 is running
Thread 11 is running
Thread 13 is running
Thread 18 is running
Thread 17 is running
Thread creation by implementing the Runnable Interface
We create a new class which implements java.lang.Runnable interface and
override run() method. Then we instantiate a Thread object and call start() method on
this object.
Example:
Class MultithreadingDemo implements Runnable {
public void run(){
try {
System.out.println(
“Thread “ + Thread.currentThread().getId()
+ “ is running”);
}
catch (Exception e){
System.out.println(“Exception is caught”);
}
}
}
class Multithread {
public static void main(String[] args) {
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
Thread object
= new Thread(new MultithreadingDemo());
object.start();
}
}
Output
Thread 13 is running
Thread 11 is running
Thread 12 is running
Thread 15 is running
Thread 14 is running
Thread 18 is running
Thread 17 is running
Thread 16 is running
Thread Class vs Runnable Interface
•If we extend the Thread class, our class cannot extend any other class because Java doesn’t support
multiple inheritance. But, if we implement the Runnable interface, our class can still extend other base
classes.
•We can achieve basic functionality of a thread by extending Thread class because it provides some
inbuilt methods like yield(), interrupt() etc. That are not available in Runnable interface.
•Using runnable will give you an object that can be shared amongst multiple threads.
Thank you!

More Related Content

PPTX
Module 4_CSE3146-Advanced Java Programming-Anno_Lambda-PPTs.pptx
PPTX
M251_Meeting_ jAVAAAAAAAAAAAAAAAAAA.pptx
PPTX
Ch-2ppt.pptx
PPT
JAVA CONCEPTS
PPTX
Unit-2.Arrays and Strings.pptx.................
PPTX
CH1 ARRAY (1).pptx
PDF
oblect oriented programming language in java notes .pdf
PDF
M251_Meeting 2_updated_2.pdf(M251_Meeting 2_updated_2.pdf)
Module 4_CSE3146-Advanced Java Programming-Anno_Lambda-PPTs.pptx
M251_Meeting_ jAVAAAAAAAAAAAAAAAAAA.pptx
Ch-2ppt.pptx
JAVA CONCEPTS
Unit-2.Arrays and Strings.pptx.................
CH1 ARRAY (1).pptx
oblect oriented programming language in java notes .pdf
M251_Meeting 2_updated_2.pdf(M251_Meeting 2_updated_2.pdf)

Similar to DOC-20240812-WA0000 array string and.pptx (20)

PPT
Generics Collections
PPT
ch06.ppt
PPT
PPT
ch06.ppt
PPT
array Details
PPT
Generics collections
PDF
Java Collections Tutorials
PPTX
Arrays in programming
PPTX
Data types ^J variables and arrays in Java.pptx
PPT
Md08 collection api
PPTX
Java String
PPTX
UNIT 1 : object oriented programming.pptx
PPT
Core java by a introduction sandesh sharma
PPTX
Arrays in Java with example and types of array.pptx
PDF
Java R20 - UNIT-3.pdf Java R20 - UNIT-3.pdf
PPTX
Classes objects in java
PPTX
Intro to C# - part 2.pptx emerging technology
PDF
4java Basic Syntax
PDF
Arrays and function basic c programming notes
PDF
Java arrays (1)
Generics Collections
ch06.ppt
ch06.ppt
array Details
Generics collections
Java Collections Tutorials
Arrays in programming
Data types ^J variables and arrays in Java.pptx
Md08 collection api
Java String
UNIT 1 : object oriented programming.pptx
Core java by a introduction sandesh sharma
Arrays in Java with example and types of array.pptx
Java R20 - UNIT-3.pdf Java R20 - UNIT-3.pdf
Classes objects in java
Intro to C# - part 2.pptx emerging technology
4java Basic Syntax
Arrays and function basic c programming notes
Java arrays (1)
Ad

Recently uploaded (20)

PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
Weekly quiz Compilation Jan -July 25.pdf
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
RMMM.pdf make it easy to upload and study
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PPTX
Radiologic_Anatomy_of_the_Brachial_plexus [final].pptx
PDF
Yogi Goddess Pres Conference Studio Updates
PPTX
Cell Structure & Organelles in detailed.
PDF
ChatGPT for Dummies - Pam Baker Ccesa007.pdf
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PPTX
UV-Visible spectroscopy..pptx UV-Visible Spectroscopy – Electronic Transition...
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
01-Introduction-to-Information-Management.pdf
PDF
Classroom Observation Tools for Teachers
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
PPTX
master seminar digital applications in india
PPTX
Microbial diseases, their pathogenesis and prophylaxis
STATICS OF THE RIGID BODIES Hibbelers.pdf
Weekly quiz Compilation Jan -July 25.pdf
Final Presentation General Medicine 03-08-2024.pptx
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
RMMM.pdf make it easy to upload and study
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Radiologic_Anatomy_of_the_Brachial_plexus [final].pptx
Yogi Goddess Pres Conference Studio Updates
Cell Structure & Organelles in detailed.
ChatGPT for Dummies - Pam Baker Ccesa007.pdf
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
202450812 BayCHI UCSC-SV 20250812 v17.pptx
UV-Visible spectroscopy..pptx UV-Visible Spectroscopy – Electronic Transition...
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
01-Introduction-to-Information-Management.pdf
Classroom Observation Tools for Teachers
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
master seminar digital applications in india
Microbial diseases, their pathogenesis and prophylaxis
Ad

DOC-20240812-WA0000 array string and.pptx

  • 1. Unit - III ARRAYS ,STRINGS AND VECTORS
  • 2. Introduction to arrays: •Array- group of a related data items that are common name. •Index-to indicate the particular value. Example: salary[100] •Individual values are called the elements.
  • 3. The values are assigned as follows: Number [0]=40; Number[1] = 55; Number [2]=63; Number [3]=17; Number [4]=22; Number [5]=68; Number [6]=89; Number [7]=97; Number [8]=89; Creating an array: Array should be declared and created before they are used. Creation of array consist of three steps: 1. Declaring the array 2. Creating memory locations 3.putting values into memory locations. Declaring the array: The general form of a one-dimensional array declaration is Example ; type var-name[]; type[] var-name;
  • 4. Creation of arrays: New operator is used Syntax: Array name= new type[size]; Number = new int [5]; Initialization of arrays: Initialisation put values into created array. Two ways: 1.syntax: Array name[subscript] = value; 2.syntax: Type array name [] = { list of values}; •Array initialisation- list of values are separated by Sunday surrounded by curly braces. Example: Int num[]= {10,20,30,40,50}
  • 5. Example: Import java.io.*; class arraysize { public static void main (String[] args) { int [] arr=new int [4]; System.out.println(“Array Size:”+arr.length); } } Output Array Size:4 Two dimensional array: It have different rows and columns Syntax: datatype [][] arrayrofvariable; datatype arrayrofvariable[][];
  • 6. Example: Public class multiDimensional { public static void main(String args[]) { int arr[][] = { { 2, 7, 9 }, { 3, 6, 1 }, { 7, 4, 2 } for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) System.out.print(arr[i][j] + “ “); System.out.println(); } } } Output 2 7 9 3 6 1 7 4 2
  • 7. STRING:  Sequence of characters.  Character array-easiest way to represent the strings. Strings are the type of objects that can store the character of values and in Java, every character is stored in 16 bits. Example: String name = “Geeks”;
  • 8. Ways of creating a string: There are two ways to create a string in Java: •String Literal •Using new Keyword. Syntax: <String_Type> <string_variable> = “<sequence_of_string>”; 1. String literal To make Java more memory efficient (because no new objects are created if it exists already in the string constant pool). Example: String demoString = “helloworld”; 2. Using new keyword String s = new String(“Welcome”); In such a case, JVM will create a new string object in normal (non-pool) heap memory and the literal “Welcome” will be placed in the string constant pool. The variable s will refer to the object in the heap (non- pool) Example: String demoString = new String (“helloworld”);
  • 9. String arrays: Users can Also create and use arrays that contains string String itemarray [] = new string []; String methods: S2= S1.to lowercase;  converts the string s1 to all lowercase. S2=S1.to uppercase;  converts the string S1 to all uppercase S2=S1.replace(‘X’ , ‘Y’) replace all appearance to X with Y S2=S.trim() remove white space at the beginning and end of the string S1. S1.equals Or ignore case(S2) returns true.if S1=S2. Ignoring the case of characters. S1.length() gives the length of S1. CharSequence Interface . CharSequence Interface is used for representing the sequence of Characters in Java. Classes that are implemented using the CharSequence interface are mentioned below and these provides much of functionality like substring, lastoccurence, first occurence, concatenate. 1.String 2.StringBuffer 3 .StringBuilder
  • 10. •String: . String is an immutable class which means a constant and cannot be changed once created. Syntax: String str= “hello”; •String buffer: StringBuffer is a peer class of String, it is mutable in nature and it is thread safe class .we can use it when we have multi threaded environment and shared object of string buffer . Syntax: StringBuffer demoString = new StringBuffer(“hello”); • String builder StringBuilder in Java represents an alternative to String and StringBuffer Class, as it creates a mutable sequence of characters and it is not thread safe. Syntax: StringBuilder demoString = new StringBuilder(); demoString.append(“hello”);
  • 11. Example: Import java.io.*; class string { public static void main(String[] args) { String name = “Sachin”; name = name.concat(“ Tendulkar”); System.out.println(name); } } Output: Sachin Tendulkar Vectors: The Vector class implements a growable array of objects. Vectors fall in legacy classes, but now it is fully compatible with collections. It is found in java.util package and implement the List interface, so we can use all the methods of the List interface.
  • 12. •Vector implements a dynamic array which means it can grow or shrink as required. Like an array, it contains components that can be accessed using an integer index. •They are very similar to ArrayList Syntax: Vector variable= new vector ();
  • 13. Methods Description 1). List.addElement(item) Adds the item specified to the list at the end. 2). List.elementAt(10) Gives the name of the 10th object 3). List.size() Gives the number of object . 4). List.copyInto(array) Copies all items from list to array. 5). List.removesAllElements() Removed all the element from the list.
  • 14. Wrapper classes: Convert primitive data types into object types. •Primitive Data Type. • Wrapper class char character byte Byte short Short int Integer long Long float. Float double Double boolean Boolean Autoboxing and unboxing: •converting primitive data types to wrapper classes is called autoboxing. •from rapper class two primitive classes is called unboxing. •null type to any primitive type . •convert to the null type other than the identity conversion. • convert from any class type c to any array type. Enumerated: Uses enum keyword .enumeration is a class type. Although we don’t need to instantiate an enum using new, it has the same capabilities as other classes. This fact makes Java enumeration a very powerful tool. Just like classes, you can give them constructors, add instance variables and methods, and even implement interfaces.
  • 15. Import java.util.Scanner; enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY; } Public class Test { Day day; public Test(Day day) { this.day = day; } public void dayIsLike() { switch (day) { case MONDAY: System.out.println(“Mondays are bad.”); break; case FRIDAY: System.out.println(“Fridays are better.”); break;
  • 16. Case SATURDAY: case SUNDAY: System.out.println(“Weekends are best.”); break; default: System.out.println(“Midweek days are so-so.”); break; } } public static void main(String[] args) { String str = “MONDAY”; Test t1 = new Test(Day.valueOf(str)); t1.dayIsLike(); } } Output Mondays are bad.
  • 17. Annotations: •Annotations are used to provide supplemental information about a program. •Annotations start with ‘@’. •Annotations do not change the action of a compiled program. •Annotations help to associate metadata (information) to the program elements i.e. Instance variables, constructors, methods, classes, etc. •Annotations are not pure comments as they can change the way a program is treated by the compiler.
  • 18. Annotation 1: @Deprecated It is a marker annotation. It indicates that a declaration is obsolete and has been replaced by a newer form. Annotation 2: @Override It is a marker annotation that can be used only on methods. A method annotated with @Override must overrid a method from a superclass. If it doesn’t, a compile-time error will result (see this for example). It is used to ensure that a superclass method is actually overridden, and not simply overloaded. Annotation 3: @SuppressWarnings It is used to inform the compiler to suppress specified compiler warnings. The warnings to suppress are specified by name, in string form. This type of annotation can be applied to any type of declaration. . Java groups warnings under two categories. They are deprecated and unchecked. Any unchecked warning is generated when a legacy code interfaces with a code that uses generics. Annotation 4: @Documented It is a marker interface that tells a tool that an annotation is to be documented. Annotations are not included in ‘Javadoc’ comments. The use of @Documented annotation in the code enables tools like Javadoc to process and include the annotation type information in the generated document. Annotation 5: @Target It is designed to be used only as an annotation to another annotation. @Target takes one argument, which mus be constant
  • 19. Interfaces: multiple inheritance Java provides the concept of interfaces to support multiple inheritance. Java class cannot be sub class of more than one class. It can be implement more than one interface. Defining interfaces: Interfaces is basically a kind of class. Interfaces contain methods and variables but no coding to implement these methods and variables Syntax: Interface interface name { Variable declaration; Method declaration; } To declare an interface, use the interface keyword. It is used to provide total abstraction. That means all the methods in an interface are declared with an empty body and are public and all fields are public, static, and final by default. A class that implements an interface must implement all the methods declared in the interface. To implement the interface, use the implements keyword. Annotation 6: @Inherited @Inherited is a marker annotation that can be used only on annotation declaration. It affects only annotations that will be used on class declarations. @Inherited causes the annotation for a superclass to be inherited by a subclass. Therefore, when a request for a specific annotation is made to the subclass, if that annotation is not present in the subclass, then its superclass is checked. If that annotation is present in the superclass, and if it is annotated with @Inherited, then that annotation will be returned.
  • 20. Extending Interfaces •One interface can inherit another by the use of keyword extends. When a class implements an interface that inherits another interface, it must provide an implementation for all methods required by the interface inheritance chain. Example: Interface Student { public void data(); } class avi implements Student { public void data () { String name=“avinash”; int rollno=68; System.out.println(name); System.out.println(rollno); } } public class inter_face { public static void main (String args []) { avi h= new avi(); h.data(); } } Output avinash 68
  • 21. Multiple Inheritance in Java Using Interface Multiple Inheritance is an OOPs concepts that can’t be implemented in Java using classes. But we can use multiple inheritances in Java using Interface. Let us check this with an example. Relationship Between Class and Interface A class can extend another class similar to this an interface can extend another interface. But only a class can extend to another interface, and vice-versa is not allowed.
  • 22. Packages: Grouping up of variety of classes and interfaces together. Packages acts as a container for classes. Classes contained in the package of other programs can be used. Types of packages: Built-in Packages These packages consist of a large number of classes which are a part of Java API.Some of the commonly used built-in packages are: •java.lang: Contains language support classes(e.g classes which defines primitive data types, math operations). This package is automatically imported. Java.io: Contains classes for supporting input / output operations. Java.util: Contains utility classes which implement data structures like Linked List, Dictionary and support ; for Date / Time operations. Java.applet: Contains classes for creating Applets. Java.awt: Contain classes for implementing the components for graphical user interfaces (like button , ;menus etc). 6) java.net: Contain classes for supporting networking operations
  • 23. User-defined packages: These are the packages that are defined by the user. First we create a directory myPackage (name should be same as the name of the package). Then create the MyClass inside the directory with the first statement being the package names. Package naming conventions : Packages are named in reverse order of domain names, i.e., org.geeksforgeeks.practice. For example, in a college, the recommended convention is college.tech.cse, college.tech.ee, college.art.history, etc. Adding a class to a Package : We can add more classes to a created package by using package name at the top of the program and saving it in the package directory. We need a new java file to define a public class, otherwise we can add the new class to an existing .java file and recompile it. Subpackages: Packages that are inside another package are the subpackages. These are not imported by default, they have to imported explicitly. Also, members of a subpackage have no access privileges, i.e., they are considered as different package for protected and default access specifiers. Example : import java.util.*; util is a subpackage created inside java package.
  • 24. Accessing classes inside a package Consider following two statements : Import java.util.vector; import java.util.*; First Statement is used to import Vector class from util package which is contained inside java. Second statement imports all the classes from util package. Example: Import java.util.Vector; public class ImportDemo { public ImportDemo() { Vector newVector = new Vector(); Java.util.ArrayList newList = new java.util.ArrayList(); } public static void main(String arg[]) { new ImportDemo(); } }
  • 31. Multithreading programming: Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU. Each part of such program is called a thread. So, threads are light-weight processes within a process. Threads can be created by using two mechanisms : 1.Extending the Thread class 2.Implementing the Runnable Interface Thread creation by extending the Thread class We create a class that extends the java.lang.Thread class. This class overrides the run() method available in the Thread class. A thread begins its life inside run() method. We create an object of our new clas and call start() method to start the execution of a thread. Start() invokes the run() method on the Thread object.
  • 32. Example: Class MultithreadingDemo extends Thread { public void run() { try { System.out.println( “Thread “ + Thread.currentThread().getId() + “ is running”); } catch (Exception e) { System.out.println(“Exception is caught”); } } } public class Multithread { public static void main(String[] args) { int n = 8; for (int i = 0; i < n; i++) { MultithreadingDemo object = new MultithreadingDemo(); object.start(); } } }
  • 33. Output: Thread 15 is running Thread 14 is running Thread 16 is running Thread 12 is running Thread 11 is running Thread 13 is running Thread 18 is running Thread 17 is running Thread creation by implementing the Runnable Interface We create a new class which implements java.lang.Runnable interface and override run() method. Then we instantiate a Thread object and call start() method on this object.
  • 34. Example: Class MultithreadingDemo implements Runnable { public void run(){ try { System.out.println( “Thread “ + Thread.currentThread().getId() + “ is running”); } catch (Exception e){ System.out.println(“Exception is caught”); } } } class Multithread { public static void main(String[] args) { int n = 8; // Number of threads for (int i = 0; i < n; i++) { Thread object = new Thread(new MultithreadingDemo()); object.start(); } }
  • 35. Output Thread 13 is running Thread 11 is running Thread 12 is running Thread 15 is running Thread 14 is running Thread 18 is running Thread 17 is running Thread 16 is running Thread Class vs Runnable Interface •If we extend the Thread class, our class cannot extend any other class because Java doesn’t support multiple inheritance. But, if we implement the Runnable interface, our class can still extend other base classes. •We can achieve basic functionality of a thread by extending Thread class because it provides some inbuilt methods like yield(), interrupt() etc. That are not available in Runnable interface. •Using runnable will give you an object that can be shared amongst multiple threads.