0% found this document useful (0 votes)
784 views6 pages

Java Basics: A Beginner's Guide

This document contains notes on Java programming concepts like functions, classes, variables, data types, input/output etc. It provides sample code to demonstrate these concepts and includes questions and answers for homework problems involving basic programming tasks like calculating area of a circle, printing tables, building a calculator etc. The document is intended to teach Java programming fundamentals to beginners.

Uploaded by

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

Java Basics: A Beginner's Guide

This document contains notes on Java programming concepts like functions, classes, variables, data types, input/output etc. It provides sample code to demonstrate these concepts and includes questions and answers for homework problems involving basic programming tasks like calculating area of a circle, printing tables, building a calculator etc. The document is intended to teach Java programming fundamentals to beginners.

Uploaded by

Shaziaa Anwer
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

JAVA NOTES

1. Sample Code

Functions
A function is a block of code which takes some input, performs some operations and
returns some output.
The functions stored inside classes are called methods.
The function we have used is called main (return type: void).

Class
A class is a group of objects which have common properties. A class can have some
properties and functions (called methods).
The class we have used is Main.

Our 1st Program

public class Main {

public static void main(String[] args) {


// Our 1st Program
[Link]("Hello World");
}
}

Question: How is my code running?


Answer: There are two stages:

(a) Compilation: There is a component known as JRE ( Java Runtime Environment) in


JDK (Java Development Kit) that we installed. There is one more component inside of
JRE known as JVM (Java virtual Machine). Our source code(extension: .java) goes to
the compiler in JDK and this compiler converts this source code into byte code
(extension: .class). This byte code can run on any operating system as long as that
system contains JRE. You cannot do this on C++, that's why Java is called a
portable language, You can run apps made by java on any operating system.

(b) Execution: JVM converts byte code into native code ( code machine can
understand), now any sytem can understand this code.
___________________________________________________________________________________
__________________________________________________

3. Variables & Data Types

3.1 Variables
A variable is a container (storage area) used to hold data.
Each variable should be given a unique name (identifier).

package [Link];

public class Main {

public static void main(String[] args) {


// Variables
String name = "Aman";
int age = 30;

String neighbour = "Akku";


String friend = neighbour;
}
}

3.2 Data Types


Data types are declarations for variables. This determines the type and size of
data associated with variables which is essential to know since different data
types occupy different sizes of memory.

There are 2 types of Data Types :


Primitive Data types : to store simple values
Non-Primitive Data types : to store complex values

3.2.1 Primitive Data Types


These are the data types of fixed size.

Eg: byte(1), short(2), int(4), char(2), boolean(1), long(8), float(4),


double(8). (size is in bytes)

3.2.2 Non-Primitive Data Types


These are of variable size & are usually declared with a ‘new’ keyword.

Eg : String, Arrays

String name = new String("Aman");


int[] marks = new int[3];
marks[0] = 97;
marks[1] = 98;
marks[2] = 95;

3.3 Constants
A constant is a variable in Java which has a fixed value i.e. it cannot be assigned
a different value once assigned.

package [Link];

public class Main {

public static void main(String[] args) {


// Constants
final float PI = 3.14F;
}
}

3.4 Output in Java

[Link]. print("Hello World");


[Link]("Hello World");
[Link]("Hello World \n");

- "System" is a class.
- "print" is a function where cursor remains in the same line same place.
- "println" is also a function where cursor moves to the next line.
- "\n" also moves the cursor to the next line.
- every command in java ends with semi colon ; ,
- single quotes can be used instead of double quotes. (but double quotes is
preferred in java)
3.5 Input in Java

import [Link].*;

public class Main {


public static void main(String[] args) {
Scanner sc= new Scanner([Link]);
String name = [Link](); //input name
[Link](name);

- [Link] only accepts only one token.


- [Link] accepts n no. of token.
- [Link] inputs integer data type.
- [Link] inputs float data type.

Question: Take two variables a and b from the user and print their sum.
Answer: import [Link].*;
public class Main {
public static void main(String[] args) {
Scanner sc= new Scanner([Link]);
int a= [Link]();
int b= [Link]():
int sum= a+b;
[Link]("Sum of the two no. is:", sum);

Homework Problems
1. Try to declare meaningful variables of each type. Eg - a variable named age
should be a numeric type (int or float) not byte.
Answer:
int height = 126;
bool answer = "true";
float price = 25.56;
2. Make a program that takes the radius of a circle as input, calculates its radius
and area and prints it as output to the user.
import [Link].*;
public class Main {
public static void main(String[]args) {
Scanner sc= new Scanner([Link]);
int rad= [Link];
int area = 3.14*rad*rad;
[Link]("Area of the circle is:", area);
3. Make a program that prints the table of a number that is input by the user.
import [Link].*;
public class Main {
public static void main(String[]args) {
Scanner sc= new Scanner([Link]);
int num=[Link];
int one= num*1;
int two= num*2;
int three= num*3;
int four= num*4;
int five=num*5;
int six=num*6;
int seven=num*7;
int eight=num*8;
int nine=num*9;
int ten=num*10;
[Link]("The table of this number is:", one);
[Link](two);
[Link](three);
......

___________________________________________________________________________________
__________________________________________________

Q) Ask the user to enter the number of the month & print the name of the month. For
eg - For ‘1’ print ‘January’, ‘2’ print ‘February’ & so on.
import [Link].*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a month's no.");
int num= [Link]();
switch(num) {
case 1: [Link]("January");
break;
case 2: [Link]("February");
break;
case 3: [Link]("March");
break;
case 4: [Link]("April");
break;
case 5: [Link]("May");
break;
case 6: [Link]("June");
break;
case 7: [Link]("July");
break;
case 8: [Link]("August");
break;
case 9: [Link]("September");
break;
case 10: [Link]("October");
break;
case 11: [Link]("November");
break;
case 12: [Link]("December");
break;
default: [Link]("Invalid");
}
}
}

Q) Make a Calculator. Take 2 numbers (a & b) from the user and an operation as
follows :
1 : + (Addition) a + b
2 : - (Subtraction) a - b
3 : * (Multiplication) a * b
4 : / (Division) a / b
5 : % (Modulo or remainder) a % b
Calculate the result according to the operation given and display it to the user.
import [Link];
import [Link].*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter first number");
int a= [Link]();
[Link]("Enter second number");
int b= [Link]();
[Link]("Enter an operator");
char op= [Link]().charAt(0);
switch (op) {
case '+': int add= a+b;
[Link](add);
break;
case '-': int sub= a-b;
[Link](sub);
break;
case '*': int mul= a*b;
[Link](mul);
break;
case '/': int div= a/b;
[Link](div);
break;
case '%': int mod= a%b;
[Link](mod);
break;

default:
[Link]("Invalid Operator");

}
}
}

Q) Print all even numbers till n.

import [Link].*;
public class Main {
public static void main(String[] args) {
Scanner sc= new Scanner([Link]);
[Link]("Enter a no.");
int n= [Link]();
for(int i=2; i <= n; i= i+2 ) {
[Link](i);
}

Common questions

Powered by AI

The 'main' method in Java is typically declared with 'public static void' for specific reasons tied to its role in program execution. 'Public' ensures that the method is accessible to the JVM from outside the class since the JVM needs to call this method to start the application. 'Static' means that the method belongs to the class rather than instances of the class, allowing the JVM to invoke it without needing to instantiate the class. 'Void' specifies that the method does not return a value, aligning with its sole purpose of providing an entry point rather than returning data. These specifications enable the systematic and consistent initiation of programs across Java environments .

In Java, System.out.print, System.out.println, and '\\n' are all used for output formatting but differ in their effects on cursor positioning. System.out.print outputs text without moving the cursor to a new line after the text, allowing subsequent print operations to continue on the same line. In contrast, System.out.println outputs the text and then moves the cursor to the beginning of the next line, enabling clean line separations in outputs. The '\\n' sequence serves as a newline character, moving the cursor to the line's start independently within the same print command, often used for embedding line breaks in strings intentionally. These options provide flexibility in how developers choose to display text output .

The 'main' method is a special method in a Java program, serving as the entry point of any standalone Java application. It is defined with a specific signature: public static void main(String[] args). This method is crucial because the Java Virtual Machine (JVM) invokes it to run the program. Unlike other functions, 'main' must always be declared as static because it needs to be accessible for execution without instantiating the class. Other methods, while also important, do not share this requirement and can have various accessibility and instantiation conditions .

The Java Scanner class is part of the java.util package and facilitates user input by allowing the program to parse primitive types and strings using regular expressions. It supports input methods like nextInt(), nextFloat(), and nextLine(), each tailored to accept specific data types: integers, floating numbers, and strings, respectively. However, its limitations include the inability to easily handle large-scale or complex input data, potential issues with newline characters when switching between nextLine() and other nextX() methods, and its reliance on exceptions for error handling. These factors make it less suitable for more extensive data-processing tasks compared to more complex I/O classes .

Control structures like switch-case in Java provide a more readable and manageable way to execute a block of code among many given conditions. A switch statement tests an expression and executes code corresponding to the matched case. For instance, using month numbers, you can map each number to its respective month with clear and concise code: 'case 1: System.out.println("January"); break;' and so on. This structure is typically more efficient and legible than multiple if-else statements, especially when dealing with numerous potential conditions like the twelve months of the year .

Java's status as a portable language is primarily due to its compilation and execution process. During compilation, the Java source code is converted into bytecode by the compiler. This bytecode is an intermediate representation that can be executed on any operating system that has a Java Runtime Environment (JRE) installed. The JRE includes the Java Virtual Machine (JVM), which interprets this bytecode into native machine code that the operating system can understand, making Java programs platform-independent .

In Java, declaring a variable with the 'final' keyword turns it into a constant, meaning its value cannot be changed once it's assigned. This ensures that crucial variables which should not change are protected from modification, thus maintaining the program's integrity and reliability. For example, constants like PI = 3.14F are declared final to prevent accidental changes that could lead to calculation errors. The use of final fields ensures consistent and predictable behavior throughout the program .

The primary differences between primitive and non-primitive data types in Java are in their size and usage. Primitive data types have a fixed size and are used to store simple values such as integers and characters. Examples include int, byte, char, and boolean. Non-primitive data types, on the other hand, have variable sizes and are used to store complex data structures like arrays and strings. They are usually declared using the 'new' keyword, such as String and int[].

The Java Virtual Machine (JVM) enhances the execution of Java programs across different operating systems by serving as a universal execution platform. It interprets bytecode, which is generated during the compilation of a Java program, into machine code appropriate for the host operating system. This abstraction layer enables Java applications to run without modification on any system with a compatible JVM installed, thus fulfilling Java’s 'write once, run anywhere' promise. This portability is a defining feature that supports widespread Java deployment across diverse environments .

Java ensures type safety through strict compile-time checking and the use of well-defined data types and casting rules. Variables in Java are declared with specific data types, which the compiler enforces, thus preventing unintended operations such as mixing incompatible types like integers and strings during calculations. Additionally, Java provides safe conversions and checks for type correctness, helping to catch errors early in the development process. Type safety is crucial for program stability because it reduces runtime errors, thereby making the software more predictable and reliable in production environments .

You might also like