0% found this document useful (0 votes)
3 views19 pages

Java M1-P2

The document provides an overview of Java programming concepts, including object declaration, arrays, data types, loops, and user input methods. It discusses the structure and limitations of arrays, the use of the Scanner and BufferedReader classes for input, and the differences between these input methods. Additionally, it covers exception handling related to arrays and the characteristics of various data types in Java.

Uploaded by

lenovo ji
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views19 pages

Java M1-P2

The document provides an overview of Java programming concepts, including object declaration, arrays, data types, loops, and user input methods. It discusses the structure and limitations of arrays, the use of the Scanner and BufferedReader classes for input, and the differences between these input methods. Additionally, it covers exception handling related to arrays and the characteristics of various data types in Java.

Uploaded by

lenovo ji
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Java Programming

Module-1

1
Declaring Objects in Java

• classname obj name=new classname();


• New operator dynamically allocates memory for an object and returns a
reference to it. This reference is the address in memory of the object
allocated by new.

Myclass obj=new obj();


obj=new Myclass(); //allocate memory to object
Array in Java
• Arrays are dynamically allocated.

• Arrays are objects in Java, we can find their length using member length.

• A Java array variable can also be declared like other variables with [] after the data
type.

• The variables in the array are ordered and each have an index beginning from 0.

• Java array can be also be used as a static field, a local variable or a method parameter.
Array in Java
• The size of an array must be specified by an int value and not long or
short.
• The direct superclass of an array type is Object.
Object class is present in java.lang package. Every class in Java is
directly or indirectly derived from the Object class. If a Class does
not extend any other class then it is direct child class
of Object and if extends other class then it is an indirectly derived.
Hence Object class acts as a root of inheritance hierarchy in any Java
Program.
• and implements the Serializable as well as Cloneable interfaces.
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.
class Testarray1{
public static void main(String args[]){
class Testarray{ int a[]={33,3,4,5};
public static void main(String args[]){ for(int i=0;i<a.length;i++)
System.out.println(a[i]);
int a[]=new int[5]; //declaration
}}
a[0]=10;//initialization
a[1]=20;
FOR-EACH Loop
a[2]=70;
a[3]=40; class Testarray1{
a[4]=50; public static void main(String args[])
for(int i=0;i<a.length;i++) {
int arr[]={33,3,4,5};
System.out.println(a[i]);
for(int i:arr)
}} System.out.println(i);
}}
Passing Array to a member Anonymous Array in Java
function • Java supports the feature of an anonymous
array.
• No need need to declare the array while
class Testarray2{ passing an array to the method.
static void min(int arr[]){
int min=arr[0]; public class TestAnonymousArray
for(int i=1;i<arr.length;i++) {
if(min>arr[i]) static void getdata(int arr[]){
min=arr[i]; for(int i=0;i<arr.length;i++)
System.out.println(min); } System.out.println(arr[i]);
public static void main(String args[]) }
{ public static void main(String args[])
int a[]={33,3,4,5}; {
min(a);//passing array to method getdata(new int[]{10,22,44,66});
//passing anonymous array to method
}}
}}
Array Index Out Of Bounds Exception
Java Virtual Machine (JVM) throws an Array Index Out Of Bounds
Exception if length of the array in negative, equal to the array size or
greater than the array size while traversing the array.

public class TestArrayException{


public static void main(String args[]) O/P:
{ 50
60
int arr[]={50,60,70,80}; 70
for(int i=0;i<=arr.length;i++) 80
Exception in thread "main"
{ java.lang.ArrayIndexOutOfBoundsException: 4 at
System.out.println(arr[i]); TestArrayException.main(TestArrayException.java:5)
}
}
}
Class name of Array Copying a Java Array
class A
class A
{
{
public static void main(String args[]) public static void main(String[] args)
{ {
int arr[]={4,4,5}; char[] S ={'d','e','c','a','f','f',’e','i’};
char[]D=new char[7];
Class c=arr.getClass();
System.arraycopy(S,2,D,0,5);
String name=c.getName();
//public static void arraycopy(Object source_arr, int sourcePos,
System.out.println(name); Object dest_arr, int destPos, int len)
}
} System.out.println(String.valueOf(D));}}
Data Types in JAVA
Data Type Size Description
byte 1 byte -128 to 127
short 2 bytes -32,768 to 32,767
int 4 bytes -2,147,483,648 to 2,147,483,647
(-2^31) to (2^31)-1
long 8 bytes -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
-2^63 to (2^63)-1
float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits

double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits

boolean 1 bit Stores true or false values


char 2 bytes Stores a single character
In Java char data type is 2 bytes Unicode character. Unicode is a universal
international standard character encoding that is capable of representing most
of the world's written languages. Its value-range lies between '\u0000' (or 0) to
'\uffff' (or 65,535).
Loops in JAVA
Class A
class A class A
{
{
{ public static void
public static void
public static void main(String args[]) main(String args[])
main(String args[]) { {
{ for (int x = 2; x <= 4; x++) int x = 21;
int x = 1; System. out.
do
println("Value of x:" + x);
while (x <= 4) } {
{ } System.out. println("Value of
System. out. x:" + x);
println("Value of x:" + x); x++;
x++; }
} while (x < 20);
} }
} }
Enhanced for loop
➢It is inflexible and should be used only when there is a need to iterate through the elements in
sequential manner without knowing the index of currently processed element.
➢Variable is immutable when enhanced for loop is used i.e., it ensures that the values in the
array can not be modified, so it can be said as read only loop where you can’t update the
values as opposite to other loops where values can be modified.
public class Main
{
public static void main(String[] args)
{
int array[] = {1,2,3,4};
for (int x:array)
{
System. out. println(x);
}
}
Input from user-1. Scanner object
import java.util.Scanner;
class Input
• Import Scanner class {
public static void main(String[] args)
import java.util.Scanner;
{
• Create object of Scanner class Scanner input = new Scanner(System.in);
System.out.print("Enter float: "); // Getting float input
Scanner input = new Scanner(System.in);
float myFloat = input.nextFloat();
int number = input.nextInt(); System.out.println("Float entered = " +myFloat);
System.out.print("Enter Int: "); // Getting int input
int myInt = input.nextInt();
System.out.println("Int entered = " + myInt);
System.out.print("Enter text: "); // Getting String input
String myString = input.next();
//if want to add space then input.nextLine();
System.out.println("Text entered = " +myString);
}
}
Input from user-1. Scanner object
Scanner obj=new Scanner(System.in);
int a=obj.nextInt();
String s=obj.nextLine();

Somethimes in this code compiler does not accept string. Because when we store
int value like 1 cursor remains after 1 and nextLine() function starts reading the
string from the current position of the cursor, which is just a new line. To overcome
this problem, we can use like this:

int a=Integer.parseInt(obj.nextLine());
2. Using Command Line Argument
class A
{ class Main
public static void main(String args[]) {
{ public static void main(String args[])
{
for(int i=0;i<args.length;i++)
int a=Integer.parseInt(args[0]);
System.out.println(args[i]); int b=Integer.parseInt(args[1]);
} int c=a+b;
System.out.println(c);
} }
}

Javac A. java
Java A 20 30 37
O/P: 20
30
37
Using DataInputStream

import java.io.*;
class Myclass
{
public static void main(String args[])throws IOException
{
DataInputStream obj=new DataInputStream(System.in);
int a,b,c;
System.out.println("Enter any two number");
a=Integer.parseInt(obj.readLine());
b=Integer.parseInt(obj.readLine());
c=a+b;
System.out.println(c);
}
}
BufferedReader class
• BufferedReader is a Java class that reads text from the input stream. It buffers the
characters so that it can get the efficient reading of characters, arrays, etc.

• It inherits the reader class and makes the code efficient since we can read the data
line-by-line with the readline() method.

• We may have to specify the buffer size even though the default is large enough for
any purpose.

• It is always advised to wrap a BufferedReader class around any reader such as


InputStreamReaders.

public class BufferedReader extends Reader


BufferedReader class

Constructor Description

This constructor creates a buffering character-


BufferedReader(Reader reader) input stream that works on a default-size input
buffer.

It uses the specified size for the input buffer for


BufferedReader(Reader reader, int size)
buffering the character-input stream.
BufferedReader class

import java.io.*;
public class Main{

public static void main(String []args)throws IOException


{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter your name: ");
String name = reader.readLine();
int num = Integer.parseInt(reader.readLine());
System.out.println("Your name is: " + name);
System.out.println("a="+num);
}
}
Sr. No. Key Scanner Class BufferReader Class

Synchronous Scanner is not syncronous in nature BufferReader is syncronous in nature.


1 and should be used only in single During multithreading environment,
threaded case. BufferReader should be used.

Buffer Scanner has little buffer of 1 KB char BufferReader has large buffer of 8KB
2 Memory buffer. byte Buffer as compared to Scanner.

Processing Scanner is bit slower as it need to BufferReader is faster than Scanner as


3 Speed parse data as well. it only reads a character stream.

Methods Scanner has methods like nextInt(), BufferReader has methods like
4 nextShort() etc. parseInt(), parseShort() etc.

Read Line Scanner has method nextLine() to BufferReader has method readLine()
5
read a line. to read a line.

19

You might also like