0% found this document useful (0 votes)
16 views13 pages

Java Programming Basics and Concepts

Java is a popular object-oriented programming language known for its platform independence and portability, achieved through the use of Java Bytecode and the Java Virtual Machine (JVM). The document covers key concepts such as data types, variables, operators, control statements, and methods, providing a foundational understanding of Java programming. Additionally, it discusses the structure of Java classes, access modifiers, and the importance of encapsulation in object-oriented programming.

Uploaded by

Manoj Kumar
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)
16 views13 pages

Java Programming Basics and Concepts

Java is a popular object-oriented programming language known for its platform independence and portability, achieved through the use of Java Bytecode and the Java Virtual Machine (JVM). The document covers key concepts such as data types, variables, operators, control statements, and methods, providing a foundational understanding of Java programming. Additionally, it discusses the structure of Java classes, access modifiers, and the importance of encapsulation in object-oriented programming.

Uploaded by

Manoj Kumar
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

JAVA NOTES 
Debugger
Form designer etc.
Java is one of most popular high level 'Object Oriented' programming  It helps in writing code, compiling and executing java programs easily.
language and has been used widely to create various computer applications. What makes Java programs platform independent and highly
What are OOPs? portable?
Answer – OOPs stands for Object Oriented Programming, Java is an Object Java compiler translates Java Code into Java Bytecode (a highly optimized
Oriented Programming language. In an Object Oriented Programming set of instructions). When the bytecode (also called a Java class file) is to be
language, a program is a collection of objects that interact with other objects run on a computer, a Java interpreter, called the Java Virtual Machine
to solve a problem. Each object is an instance of a class. (JVM), translates the bytecode into machine code and then executes it. The
advantage of such an approach is that once a programmer has compiled a
Applications of java Java program into bytecode, it can be run on any platform (say Windows,
 Database applications Linux, or Mac) as long as it has a JVM running on it. This makes Java
 Desktop applications programs platform independent and highly portable.
 Mobile applications
To write a Java program, we need:
 Web based applications
✓ Text Editor (for writing the code),
 Games etc.
✓ Java compiler, (for compiling the code into bytecode)
What is JVM? Java Integrated Development Environments (IDES) like NetBeans IDE,
JVM stands for Java Virtual Machine which is basically a java interpreter include text editor as well as Java Compiler.
which translates the byte code into machine code and then executes it. What is NetBeans?
Java NetBeans IDE is open source IDE used for writing java code,
The advantage of JVM is that once a java program is compiled into byte
compiling and executing java programs conveniently.
code. It can be run on any platform.
What is Variable?
What is byte code?
A variable is a storage location for information whose value may vary while
• Byte code is a highly optimized intermediate code produced when a java
a programme is running. A variable is, technically speaking, the name of a
program is compiled by java compiler.
storage area in the computer’s internal memory. The data present there
• Byte code is also called java class file which is run by java interpreter
serves as the variable’s value.
called JVM.
What is Java IDE?
Java Integrated Development Environment is software development kit
equipped with int

 Text (code) editor


 Compiler
Java Variables Naming rules
Data Type Type of values Size
1. Variable names can begin with either an alphabetic character, an
underscore (_), or a dollar sign ($). byte Integer 8-bit
1. Variable names must be one word. Spaces are not allowed in short Integer 16-bit
variable names. Underscores are allowed. “total_marks” is fine but
“total marks” is not. int Integer 32-bit
2. There are some reserved words in Java that cannot be used as
long Integer 64-bit
variable names, for example – int.
3. Java is a case-sensitive language. Variable names written in capital float Floating Point 32-bit
letters differ from variable names with the same spelling but written
in small letters. double Floating Point 64-bit

4. It is good practice to make variable names meaningful. The name char Character 16-bit
should indicate the use of that variable.
boolean True or False 1-bit
5. You can define multiple variables of the same type in one statement
by separating each with a comma. String Variable
String variables, also known as alphanumeric or character variables, have
What is Datatype?
values that are interpreted as text. In other words, string variables’ values
When declaring variables, we have to specify the data type of information could be made up of letters, numbers, or symbols.
that the member will hold – integer, fractional, alphanumeric, and so on.
Example- String first_name = “Mayank”;
The type of a variable tells the compiler, how much memory to reserve
String last_name = “Saxena”;
when storing a variable of that type.
NOTE: A variable of the primitive data type char can be used to store a
Java Datatype is divided into two types –
single character. To assign a value to a char variable we enclose the
1. Primitive data types – includes byte, short, int, long, float, double, character between single quotes.
boolean and char. char middle_name = 'M';
2. Non-primitive data types – such as String, Arrays and Classes.
What is the difference between local and global variables?
3. Primitive data types
Answer – Depending on their scope, variables are divided into global
A reserved term is used to identify a primitive type, which is predefined by variables and local variables. Local variables can only be accessed within
the language. The Java programming language’s support eight primitive the function or block in which they are defined, In other hand the global
data types. variables, which can be used worldwide throughout the entire programme.
What is Operator and what are the different types of Operator? c. Assignment Operator
Answer – Operators are special symbols in a programming language and
perform certain specific operations. Java support –
a. Arithmetic Operators : +, -, *, /, %, ++, —
b. Relational Operators : ==, !=, >, <, >=, <=
c. Assignment Operators : =, +=, -=, *=, /=, %=
d. Logical Operators : &&, ||, !
a. Arithmetic Operators

b. Relational Operator d. Logical Operator


Control Statement in java - Control statements are used to control the two statements – the if else statement and the switch statement for
flow of execution of statement in a programming language. Usually, all the executing a block of code conditionally (A block of code is a sequence of
statements are executed sequentially but if we want to control the flow of statements enclosed in curly braces).
execution then we use control statement.
Control statement are divided into following three categories:
1- Selection Statement/ Conditional statement
 if
 if else
 switch case
2- Looping statement
 while
 do while a) The if Else Statement
The if statement in Java lets us execute a block of code depending upon
 for
whether an expression evaluates to true or false. The structure of the Java if
3- Jumping statement
statement is as below:
 break
if (expression) {
 continue
statements
 return
}
Example :

The expression given in the round brackets after the if keyword, is a


condition – an expression constructed using relational and logical operators.
If the condition evaluates to true, the block of code following if is executed,
otherwise not. If there is only one statement in the block after the if, the
curly braces are optional.
The structure of the Java if else statement is as shown below:
if(expression) {
statements
}
Selection Statement – Selection statement are used to execute a statement else {
based on a condition. If the given condition is true, then only the statement statements
inside it is executed otherwise the else selection is executed. Java provides }
Example : Switch statement consists of three keywords:
a. case – to check for the value which has been passed.
b. break – to break the case after execution of particular choice.
c. default – statements which will be executed when no choice matches
i.e in case of invalid choice.
Example :

if-else statements can also be nested – you can have another if-else
statement within an outer if or else statement. The example below is a
nested if.

b) Switch statement- The switch statement is used to execute a block of


code matching one value out of many possible values. The functionality is
very similar to if statement.
The structure of the Java switch statement is as follows:

Repetition Structures
Looping is used to execute a single statement or a block of statement n
times till the condition is true. In simple words we can say that loop is a
way to keep executing either a single statement or a block of statement n Example:
times till the condition is true i.e. until a given condition becomes false. Program Initialization Condition Increment/Decrement
Print 1-10 i=1 i<=10 i=i+1
Print 2-20 i=2 i<=20 i=i+2
Print 10-1 i=10 i>=1 i=i-1
Print 20-2 i=20 i>=2 i=i-2
Print table 5 i=5 i<=50 i=i+5
Example :

The ability of a computer to perform the same set of actions again and again
is called looping.
The sequence of statements that is repeated again and again is called the
body of the loop.
The test conditions that determine whether a loop is entered or exited is
constructed using relational and logical operators.
A single pass through the loop is called an iteration.
For example, a loop that repeats the execution of the body three times goes b) The Do While loop- The do while statement evaluates the test after
through three iterations. Java provides three statements – executing the body of a loop. The structure of the Java do while statement is
1. while as shown –
2. do while
3. for
a) While loop - The while statement evaluates the test before executing the
body of a loop. The structure of the Java while statement is as shown: Example :

Every loop contains three parts:


1. Initialization
2. Condition
3. Increment/Decrement
Difference between while and do-while loop.
The for Loop - The for loop is the most widely used Java loop construct.
The structure of the Java for statement is as below:

Semicolons separate the three parts of a for loop:


 The initial_value initializes the value of the loop counter.
 The test_condition tests whether the loop should be executed again.
 The loop is exited when the test condition fails. The step updates the
counter in each loop iteration.
Common Coding Errors :- Example :
1. Infinite Loops: This type of error occurs when the loop runs forever, the
loop never exits. This happens when the test condition is always true. For
example,
int number = 1;
while (number <= 5)
{
[Link]("Square of " + number);
[Link](" = " + number*number);
}
This loop will run forever since number never changes – it remains at 1.
2. Syntax Errors:
 Do not forget the semi colon at the end of the test condition in a
do-while loop. Otherwise you will get a compiler error.
 Do not place a semi colon at the end of the test condition in a
while loop.

This loop is an infinite loop - The semicolon after the while causes the
statement to be repeated as the null statement (which does nothing). If
the semi colon at the end is removed the loop will work as expected.
Common Coding Errors: We can initialize the array statically (that is at compile time) as shown
1) The for Loop Initial value is greater than the limit value and the below:
loop increment is positive. In this case, body of the loop will never double[]marks = {346, 144, 103, 256.5, 387.5};
be executed. To print all the marks, we can use a for loop, varying the loop index
2) Initial value is lesser than the limit value and the loop increment is from 0 to 4.
negative. In this case also, body of the loop will never be executed. for (int i = 0; i< 5; i++)
3) Placing a semicolon at the end of a for statement. [Link](marks[i]);
4) Executing the loop either more or less times than the desired User Defined Methods
number of times. A method in Java is a block of statements grouped together to perform a
5) Using a loop index (declared within the loop) outside the loop. specific task. A method has a name, a return type, an optional list of
parameters, and a body. The structure of a Java method is as below:

Difference between Entry control loop and Exit control loop.


Entry Control Loop –
a. Entry Control Loop tests the condition first and then executes the
body of the loop.
b. If the condition is false, Entry control loop will not execute Example :
c. Example of entry control loop are – for loop and while loop
Exit Control Loop –
a. Exit Control loop tests the condition after running a block of code.
b. If the condition is false, the Entry control loop will execute at least
one time.  The name of the method is rectangle_area.
c. Example of entry control loop are – do-while.  The method has two parameters – both of type double.
Arrays:  The body of the method has only a single statement, one that
calculates the area based on the parameters and returns it.
Arrays are variables that can hold more than one value, they can hold a list  The return type from the method is of type double.
of values of the same type.  We have declared this method as a static method. The static modifier
The two statements – declaring an array and specifying its size can also be allows us to call this method without an invoking object.
done in one statement. A method is called/invoked from another method. When a method is called,
double[] marks = new double[5]; control is transferred from the calling method to the called method. The
Now we can store five marks in the array, each element of the array is statements inside the called method's body are executed. Control is then
indexed by its position, starting from 0. So the five elements of the array are returned back to the calling method.
available at positions 0 to 4 as given below:
marks[0], marks[1], marks[2], marks[3], marks[4]
A class in Java can contain:
 Fields
 Methods
 Constructors
 Blocks
 Nested class and interface

A special return type void can be used if a method does not return any a) Constructors
value. For example, a method that just prints a string need not have a return A special method member called the constructor method is used to initialize
value can use void as the return type. the data members of the class (or any other initialization is to be done at
void print_message(String message) { time of object creation).
[Link]("The message is: "+ message); Tips : The constructor has the same name as the class, has no return
} type, and may or may not have a parameter list.
This method can be called with a statement such as Whenever a new object of a class is created, the constructor of the class is
print_message("This is a secret message!"); invoked automatically. We do not call the constructor explicitly.

Object Oriented Programming b) Access Modifiers


Java is an Object Oriented Programming (OOP) language. In an OOP In object-oriented languages, the accessibility of classes, methods, and other
language, a program is collection of objects that interact with other objects members is controlled through the use of access modifiers . Access
to solve a problem. Each object is an instance of a class. modifiers are a particular type of syntax used in programming languages
that make it easier to encapsulate components.
Public, protected, default, and private are the four types of access modifiers
in Java.
Definition: These are the keywords that determine the visibility or
accessibility of members (classes, methods and fields) in different parts of

Note : By default, all members of a class are public.


In an OOP language, such as Java, an entity such as a book in the example our code.
is referred to as a class. A class is a physical or logical entity that has c) Getter and Setter Methods
certain attributes. The title, author, publisher, genre and price are the data Private data members(fields) of a class cannot be accessed outside the
members of the class Book. Displaying book details and getting its price are class however, you can give controlled access to data members outside the
method members of the class Book.
class through getter and setter methods.
Method members can get, set or update the class data members.
 A getter method returns the value of a data member(helps in
Class Design retrieving the values of private fields with the help of return
A class is a collection of objects with similar characteristics. It serves as a statement)
model or blueprint from which things can be made. It makes sense as a  A setter method modify or set the values of private fields.
whole. It cannot be bodily.
Java Libraries It provides various utility methods for working with arrays. These
method include sorting, searching , filling and othetr operations that
A Java library is nothing more than a selection of already created classes.
make array manipulation.
Java libraries are included in the JDK and are accessible to developers
without requiring additional downloads.
Examples of built-in libraries are:-
 [Link] (basic language features) sort()method to sort an array of integers in ascending order.
 [Link] (utilities)
 [Link] (input/output operations) The binarySearch() method of the Arrays class helps us search for a
Java Standard Library specific element in the array. The parameters it needs are the array to be
 Without String, Enum, Double, etc., we cannot write any Java searched and the key element to be searched. The method returns the index
programme. Everything we need to write Java code is available to us of the array where the key is present. (When array is sorted) If the key is
through the lang library. not found in the array, the binarySearch method returns -1.
 Because util class contains the definitions of all data structures and (When array is not sorted) The binarySearch method gives a negative
collections, it is necessary in order to use data structures and value if the key cannot be found in the array.
collections in Java. Example –
 We require the io library in order to deal with pipes and read data double[] marks = {103, 144, 256.5, 346, 387.5};
from files. It enables Java programmers to use files in their int key = 346;
programmes. int index = [Link](marks,key);
a) Data Input c) String Manipulation
To take user input we use the prebuilt Scanner class. This class is Strings are used for storing text. A string variable contains a collection of
available in the [Link] package. First we import this class, characters surrounded by double quotes.
import [Link];
This method converts a string to all uppercase letters.
It allows us to read input from various sources such as the console or
files. String myStr = "Hello World";
[Link]("UpperCase:"+[Link]());

The output of the code given above will be:


HELLO WORLD
b) Array Manipulation
This class is also available in the [Link] package. First we import this
class,
import [Link];
Exception Handling
Exception handling allows us to handle errors and exceptional situations
that may occur during the execution of our program.
The basic idea in exception handling is to:
 Denote an exception block - Identify areas in the code where errors
can occur
 Catch the exception - Receive the error information
 Handle the exception - Take corrective action to recover from the
error
Java provides the following keywords to handle an exception:
1) try - A try block surrounds the part of the code that can generate
exception(s).
2) catch – The catch blocks follow a try block. A catch block contains the
exception handler - specific code that is executed when the exception
occurs. Multiple catch blocks following a try block can handle different
types of exceptions.

The optional finally block is always executed when the try block exits. This
means the finally block is executed whether an exception occurs or not.

Assertion
An assertion is a useful mechanism for effectively identifying/detecting and
correcting logical errors in a program. An assert statement states a condition
that should be true at a particular point during the execution of the program.
There are two ways to write an assertion:
1) assert expression; 1) We can convert a string into its integer value. The following statement
2) assert expression1 : expression2 converts the string “3456” into the integer3456 and stores it in the int
variable d.
Threads int d = [Link](“3456”);
Thread refers to the smallest unit of execution within a process, in turn is an 2) toString() method allows conversion from an integer value to a String.
independent program that runs in its own memory space. A multithreaded String s = [Link](3456);
programme can execute numerous tasks simultaneously for the best possible
resource utilisation on the computer. A multithreaded program consists of
two or more parts called threads each of which can execute a different task PYQs
independently at the same time. 1) State TRUE or FALSE:
In Java, threads can be created in two ways: Private data members of a class cannot be accessed outside the class
1. By extending the Thread class however, you can give controlled access to data members outside the
2. By implementing the Runnable interface class through getter and setter methods.
2) Differentiate between the following two java statements:
Wrapper Classes char Alpha= ‘A’ ; //Statement #1
Wrapper classes are a set of classes that provide an object representation for String Name= “Manish”; //Statement #2
primitive data types. By default, the primitive datatypes (such as int, float, 3) Convert the following Java code from for loop to while loop without
and so on) of Java are passed by value and not by reference. Primitive changing the logic.
datatypes may occasionally need to be passed by reference. When that int X=4, Y=3;
happens, you can use the Java wrapper classes. These classes encapsulate int Pow=1;
the primitive datatype in an object. For instance, an int variable is held by for (int i=1;i<=Y;i++)
the Integer wrapper class. Pow*=X;
Consider the following two declarations: [Link](Pow);
int a = 50; // using primitive datatype 4) Give the output for the following code:
Integer b = new Integer(50); // using wrapper class String myString = "Welcome to Java";
a) [Link] ([Link]("Session"));
b) [Link] ([Link]());
c) [Link] ([Link]("to","2"));
5) Write Java code to do the following:
i) Create an array Marks that stores values 78,65,85,91,82
ii) To print all the values of the array Marks using a loop.
iii) Display the average stored in the array Marks.
6) Exception thrown by any statement in try block in a Java program is
handled in _____________ block.
7) Which access modifier in Java is used to make a data member or a
method member of a class visible only within the class?

Key Points
8) In Java, _____________ statement is used to execute a block of code 22) How can you write multiline comments in java program?
matching one value out of many possible values. 23) Sagar has declared an array whose last element is having an
9) A/An _____________ in Java is a block of statements grouped together index/position as 10. What would be the size of this array?
to perform a specific task. 24) Write the output of following code:
10) What are the different ways to create threads in Java programming? class production {
11) With reference to Java programming language, define assertion. State int inp = 50;
any one way to write an assertion. void change(int inp) {
12) Consider the following string variables : [Link]("Change"+[Link]);
String str1 = "Hello"; inp=inp+100;
String str2 = "Java Programming"; }
Write the code statements for the following in Java : public static void main(String args[]) {
a) To display the string str1 into upper case. production po=new production();
b) To display the character at the index 6 in string str2. [Link]("before
c) To display the index of the first occurrence of letter ‘l’ in the string change"+[Link]); [Link](500);
str1. [Link]("after
d) To display the string str1 after replacing letter ‘l’ with '*'. change"+[Link]);
13) Differentiate between Entry controlled loop and Exit controlled loop. }
14) ________ method of Arrays class in Java helps us to search for a }
specific element in the array. 25) Consider the following class :
15) Predict the output : public class Stud {
[Link]("Hello"); String Rno;
[Link]("Java"); String Sname;
16) ________ keyword is used to create a new class in Java program. String Address;
17) Explain the access modifiers and their types in Java. double marks;
18) What is the difference between = and == operator in Java ? Give
void display( ){
example to support your answer.
[Link]("Rno : " +Rno);
19) Consider the following code:
int x = 1; [Link]("Student name : " +Sname);
while(x<=5); [Link]("Address : " +Address);
x = x +1; [Link]("Marks : " +marks);
(a) Name the coding error shown in the above code. }
(b) What is the reason of the error? }
(c)Write correct java code. Write a command to create a constructor of the above class that
20) What is the need of a constructor in OOP? Explain all features of a initializes the data members of a class.
constructor.
21) Write a code in java using a for loop to display all odd numbers between
1 to 10. Is for loop an entry controlled loop or exit control loop?

You might also like