0% found this document useful (0 votes)
5 views12 pages

notes @JAVA

Basic Java

Uploaded by

Santhoshini
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)
5 views12 pages

notes @JAVA

Basic Java

Uploaded by

Santhoshini
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/ 12

INTRODUCTION TO JAVA

Java is a class-based, object-oriented programming language that is designed to have


as few implementation dependencies as possible. It is intended to let application
developers write once, and run anywhere (WORA), meaning that compiled Java code can run
on all platforms that support Java without the need for recompilation. Java was first released
in 1995 and is widely used for developing applications for desktop, web, and mobile
devices. Java is known for its simplicity, robustness, and security features, making it a
popular choice for enterprise-level applications.

Java was developed by James Gosling at Sun Microsystems Inc in May 1995 and later
acquired by Oracle Corporation. It is a simple programming language. Java makes writing,
compiling, and debugging programming easy. It helps to create reusable code and modular
programs. Java is a class-based, object-oriented programming language and is designed to
have as few implementation dependencies as possible. A general-purpose programming
language made for developers to write once run anywhere that is compiled Java code can run
on all platforms that support Java.

Key features of java:

1. Platform Independent

2. Object-Oriented Programming

3. Simplicity

4. Robustness

5. Security

6. Distributed

7. Multithreading

8. Portability

9. High Performance

10. Distributed
The program creation:

The Java program can be written using a Text Editor (Notepad++ or NotePad or other
editors will also do the job.) or IDE (Eclipse, NetBeans, etc.).

FileName: TestClass.java

public class TestClass


{
// main method
public static void main(String []args)
{
// print statement
System.out.println("Hello World is my first Java Program.");
}
}

Write the above code and save the file with the name TestClass. The file should have
the .java extension.

The program compilation:

Open the command prompt, and type javac TestClass.java. javac is the command that
makes the Java compiler come to action to compile the Java program. After the command, we
must put the name of the file that needs to be compiled. In our case, it is TestClass.java. After
typing, press the enter button. If everything goes well, a TestClass.class file will be generated
that contains the byte code. If there is some error in the program, the compiler will point it
out, and TestClass.class will not be created.
SCANNER CLASS
The Scanner class in Java is part of the java.util package and is used to parse primitive
types and strings using regular expressions. It can be used to read input from various sources,
including user input from the console, files, and streams.

Key Features Of The Scanner Class

Input Sources: It can read data from different sources like InputStream, File, String, and
Readable.

Tokenization: The Scanner can split input into tokens based on whitespace or specified
delimiters.

Data Types: It provides methods to read various data types, such as int, float, double, String,
etc.

Commonly Used Methods

Creating a Scanner:

Scanner scanner = new Scanner(System.in); // For console input

Scanner fileScanner = new Scanner(new File("file.txt")); // For file input

Reading Input:

int num = scanner.nextInt(); // Reads an integer

String text = scanner.nextLine(); // Reads a line of text

double value = scanner.nextDouble(); // Reads a double

Checking for Input:

if (scanner.hasNextInt()) {

int number = scanner.nextInt();

Closing the Scanner: It's good practice to close the scanner to free up resources.

scanner.close();
DATA TYPES IN JAVA
Java is statically typed and also a strongly typed language because, in Java, each type
of data (such as integer, character, hexadecimal, packed decimal, and so forth) is predefined
as part of the programming language and all constants or variables defined for a given
program must be described with one of the Java data types.

Data types in Java are of different sizes and values that can be stored in the variable
that is made as per convenience and circumstances to cover up all test cases. Java has two
categories in which data types are segregated.

1. Primitive Data Type: such as boolean, char, int, short, byte, long, float, and double.
The Boolean with uppercase B is a wrapper class for the primitive data type boolean
in Java.

2. Non-Primitive Data Type (or) Object Data type: such as String, Array, etc.

PRIMITIVE DATA TYPES:

Primitive data are only single values and have no special capabilities. There are 8
primitive data types. They are depicted below in tabular format below as follows:

1.boolean Data Type:

The boolean data type represents a logical value that can be either true or false.
Conceptually, it represents a single bit of information, but the actual size used by the virtual
machine is implementation-dependent and typically at least one byte (eight bits) in practice.
Values of the boolean type are not implicitly or explicitly converted to any other type using
casts. However, programmers can write conversion code if needed.

Syntax: boolean booleanVar;

2. byte Data Type:

The byte data type is an 8-bit signed two’s complement integer. The byte data type is
useful for saving memory in large arrays.

Syntax: byte byteVar;


3.short Data Type:

The short data type is a 16-bit signed two’s complement integer. Similar to byte, use a
short to save memory in large arrays, in situations where the memory savings actually
matters.

Syntax: short shortVar;

4.int Data Type:

It is a 32-bit signed two’s complement integer.

Syntax: int intVar;

5. long Data Type:

The range of a long is quite large. The long data type is a 64-bit two’s complement
integer and is useful for those occasions where an int type is not large enough to hold the
desired value. The size of the Long Datatype is 8 bytes (64 bits).

Syntax: long longVar;

6. float Data Type:

The float data type is a single-precision 32-bit IEEE 754 floating-point. Use a float
(instead of double) if you need to save memory in large arrays of floating-point numbers. The
size of the float data type is 4 bytes (32 bits).

Syntax: float floatVar;

7. double Data Type:

The double data type is a double-precision 64-bit IEEE 754 floating-point. For
decimal values, this data type is generally the default choice. The size of the double data type
is 8 bytes or 64 bits.

Syntax: double doubleVar;

8. char Data Type:

The char data type is a single 16-bit Unicode character with the size of 2 bytes (16
bits).

Syntax: char charVar;


// Example program using all primitive data types:

public class PrimitiveDataTypesExample {


public static void main(String[] args) {
byte byteValue = 100;
short shortValue = 30000;
int intValue = 200000;
long longValue = 15000000000L;
float floatValue = 5.75f;
double doubleValue = 19.99;
char charValue = 'A';
boolean booleanValue = true;
System.out.println("Byte Value: " + byteValue);
System.out.println("Short Value: " + shortValue);
System.out.println("Integer Value: " + intValue);
System.out.println("Long Value: " + longValue);
System.out.println("Float Value: " + floatValue);
System.out.println("Double Value: " + doubleValue);
System.out.println("Character Value: " + charValue);
System.out.println("Boolean Value: " + booleanValue);
}
}
Output:
Byte Value: 100
Short Value: 30000
Integer Value: 200000
Long Value: 15000000000
Float Value: 5.75
Double Value: 19.99
Character Value: A
Boolean Value: true

Possible errors:
1. java:7: error: incompatible types: possible lossy conversion from float to int
int floatValue = 5.75f;
2. java:11: error: package system does not exist
system.out.println("Byte Value: " + byteValue);
3. java:8: error: ';' expected
double doubleValue = 19.99

NON-PRIMITIVE DATA TYPES:

The Non-Primitive (Reference) Data Types will contain a memory address of variable
values because the reference types won’t store the variable value directly in memory. They
are strings, objects, arrays, etc.
1.Strings:
Strings are defined as an array of characters. The difference between a character array
and a string in Java is, that the string is designed to hold a sequence of characters in a single
variable whereas, a character array is a collection of separate char-type entities. Unlike C/C+
+, Java strings are not terminated with a null character.
Syntax: <String_Type> <string_variable> = “<sequence_of_string>”;

//sample code using strings


class Main {
public static void main(String[] args) {
String first = "Java";
String second = "Python";
System.out.println(first);
System.out.println(second);
}
}
Output:
Java
Python
JavaScript

Possible errors:
1. incompatible types: String cannot be converted to int
int second = "Python";
2. java:2: error: <identifier> expected
class {
2.Class:

Class is a user-defined blueprint or prototype from which objects are created. It


represents the set of properties or methods that are common to all objects of one type. In
general, class declarations can include these components, in order:
Superclass: The name of the class’s parent (superclass), if any, preceded by the keyword
extends. A class can only extend (subclass) one parent.

Interfaces: A comma-separated list of interfaces implemented by the class, if any, preceded


by the keyword implements. A class can implement more than one interface.

Body: The class body is surrounded by braces, { }.

3. Object

Object is a basic unit of Object-Oriented Programming and represents real-life


entities. A typical Java program creates many objects, which as you know, interact by
invoking methods. An object consists of :

1. State : It is represented by the attributes of an object. reflects the properties of an


object.

2. Behavior : It is represented by the methods of an object. It also reflects the response


of an object to other objects.

3. Identity : It gives a unique name to an object and enables one object to interact with
other objects.

4. Interface

Like a class, an interface can have methods and variables, but the methods declared in an
interface are by default abstract (only method signature, no body).

 Interfaces specify what a class must do and not how. It is the blueprint of the
class.
 An Interface is about capabilities like a Player may be an interface and any
class
 implementing Player must be able to (or must implement) move(). So it
specifies a set of methods that the class has to implement.
 If a class implements an interface and does not provide method bodies for all
functions specified in the interface, then the class must be declared abstract.
 A Java library example is Comparator Interface . If a class implements this
interface, then it can be used to sort a collection.

5. Array
An Array is a group of like-typed variables that are referred to by a common name.
Arrays in Java work differently than they do in C/C++. The following are some important
points about Java arrays.

 In Java, all arrays are dynamically allocated.


 Since arrays are objects in Java, we can find their length using member length.
This is different from C/C++ where we find length using size.
 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 has an index beginning with 0.
 Java array can also be used as a static field, a local variable, or a method
parameter.
 The size of an array must be specified by an int value and not long or short.

//sample code using arrays

class Main {
public static void main(String[] args) {
int[] age = {12, 4, 5, 2, 5};
System.out.println("Accessing Elements of Array:");
System.out.println("First Element: " + age[0]);
System.out.println("Second Element: " + age[1]);
System.out.println("Third Element: " + age[2]);
System.out.println("Fourth Element: " + age[3]);
}
}
Output:
Accessing Elements of Array:
First Element: 12
Second Element: 4
Third Element: 5
Fourth Element: 2

Possible errors:

1. java:3: error: ']' expected


int[ age = {12, 4, 5, 2, 5};
2. java.lang.ArrayIndexOutOfBoundsException: Index 6 out of bounds for length 5
at Main.main(Main.java:5)
VARIABLES IN JAVA
In Java, Variables are the data containers that save the data values during Java
program execution. Every Variable in Java is assigned a data type that designates the
type and quantity of value it can hold. A variable is a memory location name for the
data.
 The value stored in a variable can be changed during program execution.
 Variables in Java are only a name given to a memory location. All the operations done
on the variable affect that memory location.
 In Java, all variables must be declared before use.
Types of Variables in Java:
1. Local Variables
2. Instance Variables
3. Static Variables

1.Local Variables:

 A variable defined within a block or method or constructor is called a local variable.


 The Local variable is created at the time of declaration and destroyed after exiting
from the block or when the call returns from the function.
 The scope of these variables exists only within the block in which the variables are
declared, i.e., we can access these variables only within that block.
 Initialization of the local variable is mandatory before using it in the defined scope.

//sample code using local variable


public class LocalVariableExample {
public static void main(String[] args) {
int number = 5;
printSquare(number);
}
public static void printSquare(int num) {
int square = num * num;
System.out.println("The square of " +
num + " is " + square);
}
}

Possible errors:
1. java:3: error: cannot find symbol
string number = 5;
2. java:10: error: reached end of file while parsing
3. }

2. Instance Variables:

Instance variables are non-static variables and are declared in a class outside of any
method, constructor, or block.
 As instance variables are declared in a class, these variables are created when an
object of the class is created and destroyed when the object is destroyed.
 Unlike local variables, we may use access specifiers for instance variables. If we do
not specify any access specifier, then the default access specifier will be used.

//sample code using instance variable


public class Car {
private String color;
public Car(String color)
this.color = color;
}
public void displayColor() {
System.out.println("The color of the car is: " + color);
}
public static void main(String[] args) {
Car myCar = new Car("Red");
myCar.displayColor();
}
}

3. Static Variables:

Static variables are also known as class variables.


 These variables are declared similarly to instance variables. The difference is that
static variables are declared using the static keyword within a class outside of any
method, constructor, or block.
 Unlike instance variables, we can only have one copy of a static variable per class,
irrespective of how many objects we create.
 Static variables are created at the start of program execution and destroyed
automatically when execution ends.

//sample code using static variable


public class Counter {
private static int count = 0;
public Counter() {
count++;
}
public static int getCount() {
return count; }
public static void main(String[] args) {
Counter counter1 = new Counter();
Counter counter2 = new Counter();
Counter counter3 = new Counter();
System.out.println("Total Counter instances created: " + Counter.getCount())
}
}

Possible errors:
1. java:12: error: ';' expected
Counter counter3 = new Counter()
2. java:3: error: '(' expected
private static void count = 0;

You might also like